python使用ssh连接远程服务器,并执行命令代码,pythonssh,下面的代码使用pexpe
分享于 点击 36857 次 点评:163
python使用ssh连接远程服务器,并执行命令代码,pythonssh,下面的代码使用pexpe
下面的代码使用pexpect生成一个ssh进程,然后连接远程服务器,并执行命令。
在使用下面程序之前,需要先通过easy_install pexpect
安装pexpect程序。
#!/usr/bin/env python# -*- coding: utf-8 -*-import pexpectdef ssh_cmd(ip, passwd, cmd): ret = -1 ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd)) try: i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5) if i == 0 : ssh.sendline(passwd) elif i == 1: ssh.sendline('yes\n') ssh.expect('password: ') ssh.sendline(passwd) ssh.sendline(cmd) 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
用户点评