Catching a dying process in pexpect

折月煮酒 提交于 2019-12-07 13:14:17

问题


I'm writing some pexpect stuff that's basically sending commands over telnet.

But, it's possible that my telnet session could die (due to networking problems, a cable getting pulled, whatnot).

How do I initialize a telnet session such that, if it dies, I can catch it and tell it to reconnect and then continue execution of the code where it was at.

Is this possible?


回答1:


IMHO, you're normally better-off with a currently-maintained library like exscript or telnetlib, but the efficient incantation in pexpect is:

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



回答2:


I did this, and it worked:

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

Recursion FTW?



来源:https://stackoverflow.com/questions/5602080/catching-a-dying-process-in-pexpect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!