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

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)