如何使用Python将思科Network object group配置文本转换为指定CSV格式
Cisco网络对象组配置转CSV实现方案
实现思路
- 逐行读取输入配置,识别
Network object group开头的行作为新组的起始标记 - 每个组依次读取描述行和所有关联的host条目,分别存储到对应的数据结构中
- 统计所有组中host的最大数量,确定后续需要生成的host数据行总数
- 按要求拼装CSV行:首行放所有组名,第二行放所有组描述,后续行按索引取对应组的host,无对应条目则留空
- 用Python自带的csv模块写入文件,避免特殊字符导致的格式错误
完整实现代码
import csv # 存储所有解析后的对象组信息 group_list = [] current_group = None # 读取输入配置文件 with open('input.txt', 'r', encoding='utf-8') as input_file: for raw_line in input_file: # 仅移除换行符,保留原有前后空格匹配输出格式 line = raw_line.rstrip('\n') if not line.strip(): continue # 识别新的对象组 if line.startswith('Network object group'): if current_group is not None: group_list.append(current_group) current_group = { "name": line, "description": "", "hosts": [] } # 识别描述行 elif line.strip().startswith('Description'): current_group['description'] = line # 识别host行 elif line.strip().startswith('host'): current_group['hosts'].append(line) # 追加最后一个对象组 if current_group is not None: group_list.append(current_group) # 计算最大host数量,确定需要生成的host行数 max_host_num = max(len(group['hosts']) for group in group_list) # 拼装所有CSV行 csv_content = [] # 第一行:组名 csv_content.append([group['name'] for group in group_list]) # 第二行:描述 csv_content.append([group['description'] for group in group_list]) # 后续host行 for index in range(max_host_num): row = [] for group in group_list: row.append(group['hosts'][index] if index < len(group['hosts']) else "") csv_content.append(row) # 写入输出CSV文件 with open('output.csv', 'w', encoding='utf-8', newline='') as output_file: writer = csv.writer(output_file) writer.writerows(csv_content)
使用方法
- 将你的Cisco配置保存为脚本同目录下的
input.txt文件 - 运行脚本,同目录下生成的
output.csv即为符合要求的转换结果
内容的提问来源于stack exchange,提问作者Vlad
相关产品推荐
相关产品推荐

