繁体   English   中英

如何使用 pexpect 在 CLI 上回答命令问题?

[英]How to respond to command questions on a CLI using pexpect?

我正在使用 Python 和 pexpect 来自动化网络设备的 CLI 界面。 问题是我不能使用 pexpect 发送需要“是”/“否”确认的命令。 我认为这是因为 pexpect 与问题不符。

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 将文本作为正则表达式处理。 这对于匹配不一定是常数的东西很有用。 但是,这确实意味着当您想要匹配在正则表达式语法中有意义的字符时(例如“?”、“[”和“]”),那么您需要相应地对它们进行转义。

转义预期文本后,“是”仍未被接受/发送到设备。 我通过在“是”之后发送和附加行 ('') 解决了这个问题:

child.sendline ('yes')
child.sendline('')

[]? 是正则表达式元字符(它们具有特殊含义并且不按字面匹配)。 为避免将模式解释为正则表达式,请改用child.expect_exact(your_pattern)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM