简体   繁体   English

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

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

I am using Python and pexpect to automate a CLI interface for a networking device.我正在使用 Python 和 pexpect 来自动化网络设备的 CLI 界面。 The problem is that I cannot use pexpect to send commands that require "yes"/"no" confirmation.问题是我不能使用 pexpect 发送需要“是”/“否”确认的命令。 I think this happens because pexpect does not match the question.我认为这是因为 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')

Try this:尝试这个:

import re

child.expect( re.escape("<additional text> Are You sure? [no,yes] ") )

I think (but didn't check the documentation now) that pexpect handles the text as a regular expression.我认为(但现在没有检查文档) pexpect 将文本作为正则表达式处理。 That is useful for matching things that aren't necessarily a constant.这对于匹配不一定是常数的东西很有用。 However, it does mean that when you want to match characters that have meaning in the regular expression grammar (eg '?', '[', and ']') then you need to escape them accordingly.但是,这确实意味着当您想要匹配在正则表达式语法中有意义的字符时(例如“?”、“[”和“]”),那么您需要相应地对它们进行转义。

After escaping the expected text, the "yes" was still not accepted/sent to device.转义预期文本后,“是”仍未被接受/发送到设备。 I fixed the issue by sending and additional line ('') after "yes":我通过在“是”之后发送和附加行 ('') 解决了这个问题:

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

[]? are regex meta characters (they have special meaning and are not matched literally).是正则表达式元字符(它们具有特殊含义并且不按字面匹配)。 To avoid interpreting the pattern as a regular expression, use child.expect_exact(your_pattern) instead.为避免将模式解释为正则表达式,请改用child.expect_exact(your_pattern)

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

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