python pexpect不适用于动态值

时间:2012-05-31 12:21:36

标签: python ssh pexpect

所以我有一个程序将ssh到远程服务器并启动该端的iperf服务器。 当运行它时,它将从客户端iperf切断。

当我静态提供IP地址时,它工作正常,例如:

        p=pexpect.spawn('ssh -t -x paddy@20.20.20.20 ' + iperf)

但不是在我使用的时候:

        p=pexpect.spawn('ssh -t -x paddy@'+ADDRESS+' ' + iperf)

我得到了:

'pexpect.TIMEOUT'

ADDRESS肯定会正确进行。 任何人都有任何关于什么出错的想法?​​

    #!/usr/bin/env python
import pexpect
import re
import shutil
import getpass
import struct, fcntl, os, sys, signal, time

def start_Server(iperf, password, ADDRESS):
    ssh_newkey = 'Are you sure you want to continue connecting'
    fix = ADDRESS+' ' + iperf
    p=pexpect.spawn('ssh -t -x paddy@'+ fix)
    i=p.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1)
    if i==0:
        print "I say yes"
        p.sendline('yes')
        i=p.expect([ssh_newkey,'password:',pexpect.EOF])
    if i==1: 


        pwtp = False
        trysout = True
        while pwtp == False:
            trysout = True
            p.sendline(password)
            loginStuff=p.expect(['Permission denied, please try again.','Permission denied (publickey,password).', '------------------------------------------------------------', pexpect.TIMEOUT,pexpect.EOF],1)
            if loginStuff == 0:
                password = getpass.getpass("Please enter "+ADDRESS+"'s Password")
            elif loginStuff == 1:
                print 'Sorry but you faild to login'
                sys.exit(0)
                pwtp = True
                trysout = False
            elif loginStuff == 2:
                pwtp = True
                i=3
            elif loginStuff == 4:
                pwtp = True
                pass
            else:
                pass       

    elif i==2:
        print "I either got key or connection timeout"
        pass
    elif i==4:
        print "I either got key or connection timeout"
        pass
    if i==3: #timeout
        print fix
        print ADDRESS
        print 'we find outselfs in a timeout'
        print i
        pass
    return p, password


def RepresentsInt(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False

var = raw_input("Enter the destination IP address: ")
ADDRESS = var

password = getpass.getpass("Please enter "+ADDRESS+"'s Password")        

t, password = start_Server('iperf -s', password, ADDRESS)

u, password = start_Server('iperf -u -s', password, ADDRESS)
print ADDRESS
p=pexpect.spawn('ssh -t -x paddy@20.20.20.20 iperf -u -s')
ssh_newkey = 'Are you sure you want to continue connecting'
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i == 0:
    print ssh_newkey
elif i == 1:
    print 'password:'
elif i == 2:
    print pexpect.EOF
else:
    print 'Sorry what!?'
    print i

1 个答案:

答案 0 :(得分:0)

当我从子程序中取出pexpect ssh时,它起了作用。