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执行命令后,将执行结果返回
本文介绍了一个Python脚本,用于通过SSH远程登录并执行指定命令。该脚本使用pexpect库来处理交互式会话,包括处理密码提示和连接确认。
942

被折叠的 条评论
为什么被折叠?



