python实现ssh连接执行指令的两种方式Demo

python版本:python3.7.4

Demo:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################
#author: SkyJ
#date  : 2019/7/17
################################################

import os
import sys
import string
import datetime
import time
import paramiko   #导入paramiko

hostname = "192.168.1.11"
username = "root"
password = "SkyJ"
cmdList = ['ls -l\n', 'df -h\n']

#第一种ssh连接执行指令方式
def sshRunCmd(hostname, username, password, cmdList):
    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        #创建ssh连接
        client.connect(hostname=hostname, port=22, username=username, password=password)
        # 开启ssh管道
        ssh = client.get_transport().open_session()
        ssh.get_pty()
        ssh.invoke_shell()
        #执行指令
        for cmd in cmdList:
            ssh.sendall(cmd)
            time.sleep(0.5)
            result = ssh.recv(102400)
            result = result.decode(encoding='UTF-8',errors='strict')
            print (result)
    except Exception as e:
        print ("[%s] %s target failed, the reason is %s" % (datetime.datetime.now(), hostname, str(e)))
    else:
        print ("[%s] %s target success" % (datetime.datetime.now(), hostname))
    finally:
        ssh.close()
        client.close()

#第二种ssh连接执行指令方式
def sshRunCmd2(hostname, username, password, cmdList):
    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        #创建ssh连接
        client.connect(hostname=hostname, port=22, username=username, password=password)
        #执行指令
        for cmd in cmdList:
            stdin, stdout, stderr = client.exec_command(cmd)
            result = stdout.read()
            result = result.decode(encoding='UTF-8',errors='strict')
            print (result)
    except Exception as e:
        print ("[%s] %s target failed, the reason is %s" % (datetime.datetime.now(), hostname, str(e)))
    else:
        print ("[%s] %s target success" % (datetime.datetime.now(), hostname))
    finally:
        client.close()


if __name__ == '__main__':
    sshRunCmd(hostname, username, password, cmdList)
    sshRunCmd2(hostname, username, password, cmdList)

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值