eastydude5
eastydude5

Reputation: 617

Catching a dying process in pexpect

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?

Upvotes: 3

Views: 1826

Answers (2)

Mike Pennington
Mike Pennington

Reputation: 43097

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

Upvotes: 4

eastydude5
eastydude5

Reputation: 617

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?

Upvotes: 0

Related Questions