Pexpect 是一个用来启动子程序并对其进行自动控制的纯 Python 模块。 Pexpect 可以用来和像 ssh、ftp、passwd、telnet 等命令行程序进行自动交互。def ssh_cmd(ip, user, passwd, cmd):

    result = ''

    ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, 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)

        result = ssh.read()

    except pexpect.EOF:

        print 'EOF for %s' % (ip)

        ssh.close()

    except pexpect.TIMEOUT:

        print 'TIMEOUT for %s' % (ip)

        ssh.close()


    ssh.close()

    return result