简体   繁体   English

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

[英]How to parse a CLI command output (table) in python?

I am a newbie to parsing. 我是解析新手。

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

Assume I have an engine which injects the command on the switch, and put the above output as 1 huge string in a variable named "output". 假设我有一个将命令注入开关的引擎,并将上面的输出作为1个巨大的字符串放入名为“ output”的变量中。

I would like to return a dictionary which includes only the ports number as follows: 我想返回一个仅包含端口号的字典,如下所示:

{'Ib1/11': '1/11', 'Ib1/10': '1/10', ... , }

I guess I should use the Python`s Subprocess module and regular expressions. 我想我应该使用Python的Subprocess模块​​和正则表达式。

Number of ports can vary (can be 3, 10, 20, 30, 60...). 端口数量可以变化(可以是3、10、20、30、60 ...)。

I will appreciate any kind of direction. 我将不胜感激任何方向。

Thanks, 谢谢,

Qwerty Qwerty键盘

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM