如何在python中解析CLI命令输出(表)?

2024-05-16 19:05:19 发布

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

我对语法分析是个新手。在

switch-630624 [standalone: master] (config) # show interface ib status

Interface      Description                                Speed                   Current line rate   Logical port state   Physical port state
---------      -----------                                ---------               -----------------   ------------------   -------------------
Ib 1/1                                                    14.0 Gbps rate          56.0 Gbps           Initialize           LinkUp
Ib 1/2                                                    14.0 Gbps rate          56.0 Gbps           Initialize           LinkUp
Ib 1/3                                                    2.5 Gbps rate only      10.0 Gbps           Down                 Polling

假设我有一个引擎,它在开关上注入命令,并将上面的输出作为1个大字符串放入名为“output”的变量中。在

我想返回只包含端口号的字典,如下所示:

^{pr2}$

我想我应该使用Python的Subprocess模块和正则表达式。在

端口数量可能不同(可以是3、10、20、30、60…)。在

我会感激你的任何指示。在

谢谢

Qwerty公司


Tags: masterconfigrateportshowinterfaceibstate
1条回答
网友
1楼 · 发布于 2024-05-16 19:05:19
# Did this in Python 2.7
import re

# Assume your input is in this file
INPUT_FILE = 'text.txt'

# Regex to only pay attention to lines starting with Ib
# and capture the port info
regex = re.compile(r'^(Ib\s*\S+)')
result = [] # Store results in a list
with open(INPUT_FILE, 'r') as theFile:
  for line in theFile:
    match = regex.search(line)
    if not match: continue
    result.append(match.group())
print result

相关问题 更多 >