我正在使用 Python 并期望为网络设备自动化 CLI 界面。 问题是我不能使用 pexpect 发送需要"is"/“否”确认的命令。 我认为发生这种情况是因为预期与问题不匹配。
child = pexpect.spawn ('ssh -p <port> user@192.168.1.1')
child.expect ("password: ")
child.sendline ('userPass')
child.expect ('> ')
child.sendline('show')
child.expect('> ')
logging.info(child.before)
# works fine untill now - it connects to the box and prints the show output
child.sendline ('reset')
logging.info(child.before)
# this command prints the same thing as previous child.before
logging.info('This line gets printed.')
child.expect ("<additional text> Are You sure? [no,yes] ")
logging.info('This line does not get printed.')
child.sendline ('yes')
请您参考如下方法:
试试这个:
import re
child.expect( re.escape("<additional text> Are You sure? [no,yes] ") )
我认为(但现在没有检查文档)pexpect 将文本作为正则表达式处理。这对于匹配不一定是常量的事物很有用。然而,这确实意味着当您想要匹配在正则表达式语法中有意义的字符(例如“?”、“[”和“]”)时,您需要相应地对它们进行转义。
