pexpect,脚本在需要“$”时超时

2024-10-05 17:45:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pexpect命令学习python,我试图使用ign ssh编写一个脚本到多个服务器并运行远程安装,但是当脚本运行到孩子。期待(“$”)它超时并且没有执行后续任务,可以看看可能出了什么问题?在

这是密码

#!/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得到的错误信息

^{pr2}$

在pexpect.超时:read_nonblocking()超时。在

谢谢!在


Tags: import脚本childinputrawpasswordsshpdb
1条回答
网友
1楼 · 发布于 2024-10-05 17:45:30

我刚碰到这个问题,@jfs的评论节省了我很多调试时间。在

问题是对child.expect('$')的调用。因为pexpect在默认情况下使用regex匹配,而且$是regex中的“行尾”元字符,所以它希望在那里找到行尾而不是文本$。在

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

注意:如果@jfs发布了一个答案,我很乐意把我的答案记下来,这样他们就能得到所有的荣誉。在

相关问题 更多 >