如何使用 Python 的 Pexpect 复制 Expect 的 $expect_out(1,string)?

How do I replicate Expect's $expect_out(1,string) using Python's Pexpect?

当我在 Cisco 交换机上 运行 'show version' 时,我得到以下输出:

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

<--输出 t运行cated-->

#

我正在使用 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) 以获得准确的版本?

非常感谢

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")