输入键命令有时无法正常工作

时间:2019-10-15 18:04:56

标签: python-2.7 ssh enter pexpect pxssh

我正在pexpect脚本下运行,以登录Avocent控制台服务器以连接到网络设备。输入服务器密码后,需要按“ Enter键”以出现提示。为了达到这个目的,我尝试了child.sendline()child.send('\n')child.sendcontrol ('m'),但是这些都不起作用。 我尝试了child.send('\r'),但是它间歇性地工作。不知道是什么原因引起的。

我看到当脚本在等待输入键时卡住时,如果我手动登录到控制台并通过键盘发送输入键,则pexpect脚本会继续。

这是我的代码段:

child = pexpect.spawn('ssh local@x.x.x.x', timeout=120)
child.expect('Password:', timeout=60)
child.sendline(avocentpswd)
child.send('\r')
print "enter key sent"
cli = child.expect(['cisco#' , 'cisco>'])

使用pexpect == 4.7.0 Python 2.7.5 操作系统:RHEL v7

请有人帮忙。

我检查了提出的问题,但这没有帮助: pexpect and sending an "Enter Key" issues

1 个答案:

答案 0 :(得分:0)

您可能只需要等待一两秒钟,以使ssh完成连接并将tty模式重置为echo。尝试在发送import time;time.sleep(5)之前添加\r,如果可行,请使用类似(未经测试)的循环:

for tries in range(5):
   child.send('\r')
   cli = child.expect([pexpect.TIMEOUT, 'cisco#' , 'cisco>'], timeout=1)
   if cli!=0: break
else: ... fail ...
... ok ...