paramiko远程执行命令
# encoding: utf-8
import numpy as np
import paramiko
import time
def creatSShConnectOb(hostname, username, password, port=22):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname, port, username=username, password=password, timeout=60) # timeout protection
return ssh
except:
print('Warning:\nFist connect the {} failed, now will retry!'.format(hostname))
ssh.connect(hostname, port, username=username, password=password, timeout=60) # timeout re-try
print('Error:\nAttempt to connect ABC failed!!! Please check the IP / port/ account / password.')
def chanel_exe_cmd(ChanelSSHOb, cmd, t=0.1):
ChanelSSHOb.send(cmd)
ChanelSSHOb.send("\n")
time.sleep(t)
resp = ChanelSSHOb.recv(9999).decode("utf8")
print("#"*40)
return resp
if __name__ == '__main__':
ssh = creatSShConnectOb(hostname="192.168.110.16", username="root", password="xxx")
chanelSSHOb = ssh.invoke_shell()
result = chanel_exe_cmd(chanelSSHOb, "pwd")
print(result)
result = chanel_exe_cmd(chanelSSHOb, "cd /data")
print(result)
result = chanel_exe_cmd(chanelSSHOb, "pwd")
print(result)
结果
[root@110-16 ~]# pwd
/root
[root@110-16 ~]#
########################################
cd /data
########################################
[root@110-16 data]# pwd
/data
[root@110-16 data]#
报错
ValueError: ('Invalid private key', [_OpenSSLErrorWithText(code=67764350, lib=4, func=160, reason=12
将paramiko的版本降低到2.7.2即可
paramiko无法获取全部回显
因为使用recv方法每次最多只能获取到65535字节,超过这个大小就需要循环获取
下面脚本以messages文件为例
# encoding: utf-8
import paramiko
import time # 引入 time 模块,用于延时。
def exec_command():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,22,user,password) #SSH端口默认22,可改
command = ssh.invoke_shell()
cmd = "cat /var/log/messages \n"
# cmd = "ls"
command.send(cmd)
sleep_time = 0.5
result = ""
recv_ready_status = command.recv_ready()
time.sleep(sleep_time) # 需要休眠一下,否则太快了recv里面没有数据
while recv_ready_status:
output = command.recv(65535).decode("utf-8")
result += output
time.sleep(sleep_time)
recv_ready_status = command.recv_ready()
ssh.close()
return result
if __name__ == '__main__':
result= exec_command()
print(result)