如何用Python从IOS-XE路由器命令输出提取Services值?
提取Cisco设备输出中Services对应数值的可靠方法
针对IOS-XE设备的CLI输出,以下几种方法比单纯转列表更可靠且通用:
方法1:基于列标题的位置定位
Cisco的CLI输出列是对齐排版的,可通过标题行确定"Services"列的位置,再从数据行提取对应内容:
# 假设命令输出已存入output变量 lines = [line.strip() for line in output.split('\n') if line.strip()] header_line = lines[1] # 标题行是第二行 data_line = lines[2] # 数据行是第三行 # 找到Services列的起始和结束索引 service_start = header_line.index('Services') service_end = header_line.index('Archive(min)') # 提取对应位置的内容并转成整数 services_value = int(data_line[service_start:service_end].strip()) print(services_value) # 输出1
这种方法依赖输出的列对齐特性,IOS-XE设备的同类命令输出格式基本一致,通用性较强。
方法2:正则表达式匹配
通过匹配数据行的字段格式直接捕获Services数值,适合输出格式稳定的场景:
import re output = """#show ethernet cfm domain brief Domain Name Index Level Services Archive(min) EVC 2 4 1 100""" lines = [line.strip() for line in output.split('\n') if line.strip()] # 正则匹配数据行的字段:域名、Index、Level、Services、Archive match = re.search(r'^\S+\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$', lines[2]) if match: services_value = int(match.group(3)) # 第三个捕获组对应Services print(services_value) # 输出1
如果输出存在多行数据,可改用re.findall批量提取。
方法3:使用TextFSM(最通用的专业工具)
TextFSM是专门用于解析网络设备CLI输出的工具,适合复杂或多格式的输出场景,兼容性极强:
- 先安装TextFSM:
pip install textfsm - 创建模板文件
cfm_domain_template.txt:
Value DomainName (\S+) Value Index (\d+) Value Level (\d+) Value Services (\d+) Value ArchiveMin (\d+) Start ^${DomainName}\s+${Index}\s+${Level}\s+${Services}\s+${ArchiveMin} -> Record
- Python代码解析:
import textfsm with open('cfm_domain_template.txt', 'r') as f: template = textfsm.TextFSM(f) # 解析命令输出 result = template.ParseText(output) services_value = int(result[0][3]) # 结果列表的第一个元素是数据行,第四个值对应Services print(services_value) # 输出1
这种方法可适配不同IOS-XE版本的输出格式微调,是网络运维场景下的首选方案。
内容的提问来源于stack exchange,提问作者mac
相关产品推荐
相关产品推荐

