如何从思科设备sh run输出文本文件中提取接口级配置
思科设备show run配置接口段提取实现方案
匹配规则说明
思科路由器/交换机的运行配置(show running-config/sh run输出)中,所有接口配置段遵循统一格式:
- 段起始:行首为
interface关键字,后接接口类型与编号,覆盖Port-channel/GigabitEthernet/FastEthernet/Vlan/Loopback等所有接口类型 - 段结束:单独占一行的分隔符
! - 段内为该接口下的所有子配置,存在缩进、空行属于正常情况
常见正则逻辑缺陷
自行编写的代码提取失败,通常是以下问题导致:
- 未开启多行匹配模式,无法正确识别行首的
interface和单独成行的! - 使用贪婪匹配规则,导致从第一个接口起始位置一直匹配到文件末尾的最后一个
!,混入大量非接口配置 - 未做行首锚定,把配置描述中出现的"interface"字符串误判为接口段开头
- 未做整行匹配
!的规则,被配置行内备注的!提前截断
可直接运行的Python实现代码
import re def extract_cisco_interfaces(input_file_path, output_file_path): # 读取源sh run配置文件 with open(input_file_path, 'r', encoding='ascii', errors='ignore') as f: run_config = f.read() # 核心正则:多行模式+非贪婪匹配,锚定行首interface起始、整行!结束 interface_pattern = re.compile( r'^interface .*?^!$', flags=re.MULTILINE | re.DOTALL ) # 提取所有匹配的接口配置段 interface_segments = interface_pattern.findall(run_config) # 写入目标文件,段之间加空行分隔方便阅读 with open(output_file_path, 'w', encoding='ascii') as f: for seg in interface_segments: f.write(seg + '\n\n') print(f"提取完成,共获取{len(interface_segments)}个接口配置段,已保存到{output_file_path}") # 调用示例 if __name__ == "__main__": extract_cisco_interfaces( input_file_path="sh_run_source.txt", output_file_path="interfaces_config.txt" )
匹配效果验证
以如下真实交换机配置片段为例:
! version 15.2(4)E8 hostname ACCESS_SW_03 ! interface Port-channel1 description PO1-STACK-PEER switchport trunk allowed vlan 1-4094 switchport mode trunk ! interface GigabitEthernet0/0 description UPLINK-TO-CORE-SW01-Gi0/1 ip address 10.0.0.3 255.255.255.252 no ip redirects no shutdown ! interface FastEthernet1/0/1 description AP-3F-01 switchport access vlan 20 switchport mode access power inline auto spanning-tree portfast ! line con 0 logging synchronous line vty 0 15 login local transport input ssh !
代码运行后会精准提取3个接口的完整配置段,不会混入version、hostname、line配置等无关内容。
内容的提问来源于stack exchange,提问作者Sharique
相关产品推荐
相关产品推荐

