【问题标题】:How do I replicate Expect's $expect_out(1,string) using Python's Pexpect?如何使用 Python 的 Pexpect 复制 Expect 的 $expect_out(1,string)?
【发布时间】:2017-12-01 09:54:53
【问题描述】:

当我在 Cisco 交换机上运行“显示版本”时,我得到以下输出:

Cisco IOS 软件,C3750E 软件 (C3750E-UNIVERSALK9-M),版本 12.2(58)SE2,发布软件 (fc1) 技术支持:http://www.cisco.com/techsupport Cisco Systems, Inc. 版权所有 (c) 1986-2011。

#

我正在使用 Expect 登录到交换机,运行 show version 命令,并期待该命令的完整输出和确切版本,然后我可以使用以下代码将其输出到屏幕:

send "show version\n"
expect -re "show version.*Version (.*), REL.*#$"
send_user "Command Output:\n$expect_out(0,string)\n\n"
send_user "Version:\n$expect_out(1,string)\n\n"

这一切正常,但是我现在尝试使用 Python 和 Pexpect 复制它。我可以使用 child.before 获得 $expect_out(0,string) 的等价物:

child.sendline(show version')
child.expect('#')
print("\r\n","Command Output:","\r\n",child.before, sep = '')

如何在 Pexpect 中复制 $expect_out(1,string) 以获得准确的版本?

在此先感谢

【问题讨论】:

    标签: python tcl expect pexpect


    【解决方案1】:

    Pexpect 包做的比 Expect 少,这是它完全不同的地方之一,因为没有对相关匹配对象的公开访问。

    您需要use a separate RE 提取您关心的部分。

    import re
    
    child.sendline(show version')
    child.expect('#')
    print("\r\n","Command Output:","\r\n",child.before, sep = '')
    
    m = re.search("show version.*Version (.*), REL.", child.before)
    if m:
        print("Version:\n" + m.group(1) + "\n\n")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-14
      • 2018-06-07
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      相关资源
      最近更新 更多