Python如何将交换机端口输出字符串转换为指定结构嵌套字典
解决方案
你遇到的空格错位问题是因为交换机输出是固定列对齐而非固定空格分隔,不要用split(' ')处理,推荐以下两种无第三方依赖的实现方案:
方案1:正则捕获组匹配(灵活度高)
利用正则按字段顺序编写捕获规则,空字段会自动返回None,完全适配你的格式要求:
import re from collections import defaultdict # 预定义正则匹配规则,每个括号对应一个字段,空描述也能正常捕获 PATTERN = re.compile( r'^(\S+)\s+(\S*)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$' ) # 预定义字段名,和正则捕获组顺序一一对应 FIELDS = ['Interface', 'Description', 'Duplex', 'Speed', 'Neg', 'Linkstate', 'Flowctrl', 'M', 'VLAN'] def parse_port_data(raw_str): port_dict = defaultdict(dict) for line in raw_str.splitlines(): line = line.strip() if not line or line.startswith('...'): # 跳过空行和省略标记行 continue match = PATTERN.match(line) if not match: continue # 提取所有捕获组,空字符串统一转None values = [v if v else None for v in match.groups()] # 构造单端口字典 port_info = dict(zip(FIELDS, values)) # 处理VLAN字段转列表 if port_info['VLAN']: port_info['VLAN'] = port_info['VLAN'].split(',') # 提取端口号作为key:Gi1/0/14 -> 提取14转int port_num = int(port_info['Interface'].split('/')[-1]) port_dict[port_num] = port_info return port_dict # 使用方式 port = parse_port_data(你的原始端口字符串) print(port[14]['Description']) # 直接输出COMPUTER14
方案2:固定列宽切割(稳定性最高)
交换机CLI输出基本都是严格列对齐的,你可以先数清楚每个字段的起始/结束索引,直接按位置切割字符串,完全不受空格数量影响:
# 先测量你原始输出的每个字段列范围(按自己的实际输出调整数值即可) COL_RANGES = [ (0, 9), # Interface (10, 22), # Description (23, 29), # Duplex (30, 36), # Speed (37, 43), # Neg (44, 50), # Linkstate (51, 57), # Flowctrl (58, 62), # M (63, None) # VLAN ] FIELDS = ['Interface', 'Description', 'Duplex', 'Speed', 'Neg', 'Linkstate', 'Flowctrl', 'M', 'VLAN'] def parse_port_data(raw_str): port_dict = {} for line in raw_str.splitlines(): line = line.rstrip('\n') if not line or line.startswith('...'): continue values = [] for start, end in COL_RANGES: val = line[start:end].strip() values.append(val if val else None) port_info = dict(zip(FIELDS, values)) if port_info['VLAN']: port_info['VLAN'] = port_info['VLAN'].split(',') port_num = int(port_info['Interface'].split('/')[-1]) port_dict[port_num] = port_info return port_dict
两种方案都不需要依赖TextFSM等第三方解析库,也完全规避空格数量不稳定、空字段导致的错位问题。
内容的提问来源于stack exchange,提问作者cosmis
相关产品推荐
相关产品推荐

