您的位置:首页 > 编程语言 > Python开发

python 使用ssh远程登录并执行命令返回结果

2017-09-13 16:15 1076 查看
import os
import sys
import pexpect
def remote_ssh(remote_ip, user, passwd, cmd):
ret = -1
ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, remote_ip, cmd))
try:
i = ssh.expect(['password:', 'continue connect (yes/no)?'], timeout = 5)
if i == 0:
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes\n')
ssh.expect('password:')
ssh.sendline(passwd)
r = ssh.read()
print r
ret = 0
except pexpect.EOF:
print "EOF"
ssh.close()
ret = -1
except pexpect.TIMEOUT:
print "TIMEOUT"
ssh.close()
ret = -2
return ret, r

if __name__ == "__main__":
ip = "192.168.1.83"
user = "root"
passwd = "123456"
cmd = "df -h"
ret, msg = remote_ssh(ip, user, passwd, cmd)
print ret
print msg


通过远程登陆ssh执行命令后,将执行结果返回
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: