pexpect,脚本在期待'$'时超时

时间:2016-04-15 02:32:40

标签: python pexpect spawn

我正在使用pexpect命令学习python,我正在尝试编写一个脚本,将ssh用于多个服务器并运行远程安装,但是当脚本运行到child.expect('$')时,它会超时并且不执行后续操作任务,可以看出可能出现的问题?

这是代码

#!/usr/bin/python
import pexpect
import getpass
import pdb

user = raw_input("what is username:")
paswd =getpass.getpass("Please enter your password: ")
seNam = raw_input("Server name:")

child = pexpect.spawn('ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PreferredAuthentications=\"password\" "' + user + "@" + seNam)
child.logfile = sys.stdout
child.expect('password:')
child.sendline(paswd)
child.expect('$')
child.sendline("ls -l")
child.expect('$')
child.sendline("exit")

raw_input("please press enter to continue...")

这是我从pdb获得的错误信息

Traceback (most recent call last):

File "./expecTest.py", line 23, in <module>
child.expect('$')

File "/usr/lib/python2.6/site-packages/pexpect.py", line 1311, in expect
return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)

File "/usr/lib/python2.6/site-packages/pexpect.py", line 1325, in expect_list
return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)

File "/usr/lib/python2.6/site-packages/pexpect.py", line 1409, in expect_loop
raise TIMEOUT (str(e) + '\n' + str(self))

pexpect.TIMEOUT:read_nonblocking()中超出了超时。

谢谢!

1 个答案:

答案 0 :(得分:0)

我本人只是遇到了这个问题,@ jfs的评论为我节省了很多调试时间。

问题是调用child.expect('$')。由于pexpect默认使用正则表达式匹配,并且因为$是正则表达式中的“行尾”元字符,因此希望在此处找到行尾而不是文字$

解决方案是转义符号\$,或使用与字符串文字(而不是正则表达式)匹配的child.expect_exact('$')

注意:如果@jfs发布答案,我很乐意接受我的帮助,以便他们获得所有功劳。