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

2024-05-20 17:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在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

<;--输出被截断-->

十一

我使用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来复制它。我可以使用孩子之前公司名称:

^{pr2}$

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

非常感谢


Tags: 命令版本sendstring软件versionshowout
1条回答
网友
1楼 · 发布于 2024-05-20 17:32:54

Pexpect包所做的比预期的要少,这是它的一个非常不同的方面,因为没有对相关匹配对象的公开访问。在

您需要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")

相关问题 更多 >