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

问题描述 投票:3回答:1

我正在使用pexpect命令学习python,我试图将脚本usign 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()中超出超时。

谢谢!

python pexpect spawn
1个回答
0
投票

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.