我正在写一些 pexpect 的东西,基本上是通过 telnet 发送命令。
但是,我的 telnet 会话可能会终止(由于网络问题、电缆被拉断等)。
我如何初始化一个 telnet 会话,如果它死了,我可以捕获它并告诉它重新连接,然后继续执行它所在的代码。
这可能吗?
恕我直言,您通常使用当前维护的库(如 exscript
or )会更好telnetlib
,但有效的咒语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
我这样做了,它奏效了:
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?