在pexpect中捕捉垂死的过程

时间:2011-04-09 00:36:09

标签: python expect pexpect

我正在编写一些基本上通过telnet发送命令的pexpect东西。

但是,我的telnet会话可能会死(由于网络问题,电缆被拉,等等)。

如何初始化一个telnet会话,如果它死了,我可以抓住它并告诉它重新连接,然后继续执行它所在的代码。

这可能吗?

2 个答案:

答案 0 :(得分:4)

恕我直言,您通常会使用当前维护的库exscripttelnetlib更好,但pexpect中有效的咒语是:

import pexpect as px

cmds = ['cmd1', 'cmd2', 'cmd3']
retcode = -1
while (retcode<10):
    if (retcode<2):
        child = px.spawn('telnet %s %s' % (ip_addr,port))
    lregex = '(sername:)'            # Insert regex for login prompt here
    pregex = '(prompt1>)|(prompt2$)' # Insert your prompt regex here
    # retcode = 0 for px.TIMEOUT, 1 for px.EOF, 2 for lregex match...
    retcode = child.expect([px.TIMEOUT, px.EOF, lregex, pregex],timeout = 10)
    if (retcode==2):
        do_login(child)  # Build a do_login() method to send user / passwd
    elif (2<retcode<10) and (len(cmds)>0):
        cmd = cmds.pop(0)
        child.sendline(cmd)
    else:
        retcode = 10

答案 1 :(得分:0)

我这样做了,并且有效:

def telnet_connect():
    print "Trying to connect via telnet..."
    telnet_connecting = pexpect.spawn('telnet localhost 10023', timeout=2)
    while 1:
        try:
            telnet_connecting.expect('login: ')
            break
        except:
            telnet_connecting = telnet_connect()
            break
    return telnet_connecting

递归FTW?