Python实现网络设备配置文本转Excel(新手求助)
交换机配置转Excel的Python实现方案
核心思路是按接口配置块分组——从interface开头的行开始,到下一个interface行或者文件结尾,这一段就是单个接口的完整配置,然后逐个解析每个块里的字段。
具体步骤与代码示例
- 读取并分组接口配置
用简单的状态跟踪方式,遍历配置文件的每一行,遇到interface行就开启新的接口配置块,把之前的块存入列表:
def parse_switch_config(config_path): interfaces = [] current_if = None with open(config_path, 'r') as f: for line in f: line = line.strip() if not line: continue # 跳过空行 # 遇到新接口,先把之前的接口存入列表 if line.startswith('interface'): if current_if is not None: interfaces.append(current_if) # 初始化新接口的字典,提取接口编号 if_name = line.split()[1] current_if = { '接口编号': if_name, 'Untagged Vlan': '', 'Tagged Vlan': '', 'name': '' } else: # 处理当前接口的配置项 if current_if is not None: if line.lower().startswith('untagged vlan'): current_if['Untagged Vlan'] = line.split()[-1] elif line.lower().startswith('tagged vlan'): current_if['Tagged Vlan'] = line.split()[-1] elif line.lower().startswith('name'): current_if['name'] = ' '.join(line.split()[1:]) # 把最后一个接口加入列表 if current_if is not None: interfaces.append(current_if) return interfaces
- 写入Excel文件
用openpyxl把解析后的接口数据写入Excel,对应指定列:
from openpyxl import Workbook def write_to_excel(interfaces, excel_path): wb = Workbook() ws = wb.active # 写入表头 ws.append(['接口编号', 'Untagged Vlan', 'Tagged Vlan', 'name']) # 写入每个接口的数据 for iface in interfaces: ws.append([ iface['接口编号'], iface['Untagged Vlan'], iface['Tagged Vlan'], iface['name'] ]) wb.save(excel_path) # 调用示例 if __name__ == '__main__': config_data = parse_switch_config('switch_config.txt') write_to_excel(config_data, 'switch_interfaces.xlsx')
关键细节说明
- 分组逻辑:通过
current_if变量跟踪当前正在处理的接口,确保每个接口的配置被完整收集,不管单接口配置行数多少。 - 配置项匹配:用
lower()统一转小写,避免大小写差异导致匹配失败(比如配置里写Untagged或untagged都能识别)。 - 容错处理:跳过空行,避免空行干扰解析;即使接口没有某个配置项(比如没有name),Excel对应列会留空,符合需求。
适配不同配置格式
如果你的交换机配置里的关键字不同(比如有的用switchport access vlan表示Untagged),只需要修改配置项匹配的条件即可,比如:
elif line.lower().startswith('switchport access vlan'): current_if['Untagged Vlan'] = line.split()[-1] elif line.lower().startswith('switchport trunk allowed vlan'): current_if['Tagged Vlan'] = line.split()[-1]
内容的提问来源于stack exchange,提问作者Fantaboksen
相关产品推荐
相关产品推荐

