【问题标题】:How to respond to command questions on a CLI using pexpect?如何使用 pexpect 响应 CLI 上的命令问题?
【发布时间】:2015-11-03 16:50:22
【问题描述】:

我正在使用 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')

【问题讨论】:

    标签: python python-2.7 command-line-interface pexpect


    【解决方案1】:

    试试这个:

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

    我认为(但现在没有检查文档) pexpect 将文本作为正则表达式处理。这对于匹配不一定是常数的事物很有用。但是,这确实意味着当您想要匹配在正则表达式语法中有意义的字符时(例如,'?'、'[' 和 ']'),您需要相应地对它们进行转义。

    【讨论】:

    • 是的,添加转义可以成功匹配文本。谢谢!
    【解决方案2】:

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

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

    【讨论】:

    • 问题中的代码存在几个问题。您应该尝试将您的问题限制为每个问题一个问题(即,首先尝试本地化您的问题)。否则,每个 答案应解决所有问题(它不是传统论坛)。我怀疑你的代码最后需要child.expect(pexpect.EOF); child.close()
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多