我正在学习pexpect和正则表达式。我有两个问题: 1. child.expect(这里的一些文本)真的必须是一个正则表达式吗? 2.如果有人能告诉我为什么我的脚本在密码输入时挂起,我将不胜感激。
import pexpect
import getpass
import sys
try:
switch = raw_input("Host: ")
un = raw_input("Username: ")
pw = getpass.getpass("Password: ")
child = pexpect.spawn("ssh %s@%s" % (un, switch))
child.logfile = sys.stdout
selection = child.expect(['Are you sure you want to continue connecting (yes/no)?','login as:'])
if selection == 0:
child.sendline("yes")
elif selection == 1:
i = child.expect(['login as:','user@10.0.0.65\'s password:'])
if i == 0:
child.sendline(un)
elif i == 1:
child.sendline(pw)
child.expect('Switch#')
child.sendline("show cdp nei")
except Exception as e:
print("Failed on login")
print(e)
发布于 2018-07-31 08:45:27
来自the docs
…模式可以是StringType、EOF、编译的re或这些类型的列表。字符串将被编译为re类型。…
所以,如果你像这样传递一个模式:
['Are you sure you want to continue connecting (yes/no)?','login as:']
…这是两个字符串的列表,这两个字符串都将被编译为正则表达式。因此,例如,您将有一个包含单个值yes/no
的捕获组,出现0或1次,这可能不是很有用。
如果您希望将它们作为文字字符串进行匹配,最简单的方法可能是对它们调用re.escape
:
[re.escape('Are you sure you want to continue connecting (yes/no)?'),
re.escape('login as:')]
https://stackoverflow.com/questions/51603913
复制相似问题