使用ciscoconfparse查找access口配置块中含dot1x pae authenticator的接口
代码问题修复方案
原代码存在的问题
- 配置文件路径不完整:
os.listdir()仅返回目录下的文件名,未拼接父目录路径,直接传入CiscoConfParse会触发文件找不到错误 - 正则搜索参数错误:
re.search()第二个参数错误传入了行列表all_intfs,应该传入当前遍历的单条行字符串intf - 逻辑缺项:没有关联
dot1x配置与对应接口名称的逻辑,无法输出目标接口名
修正后可运行代码
import os import csv from ciscoconfparse import CiscoConfParse # CSV文件初始化逻辑保留 result_path = r'c:\users\lang\documents\result.csv' file_exists = os.path.isfile(result_path) if not file_exists: with open(result_path, 'w', newline='') as csv_file: Header = ['Device', 'Vul ID', 'Exception', 'Status', 'Code', 'Severity', 'Reason'] writer = csv.DictWriter(csv_file, fieldnames=Header) writer.writeheader() def check_services(): configs_dir = r'C:\Users\Lang\Documents\Tutorials\Python\Scripts\NetworkAudit\Data' # 遍历所有配置文件 for config_name in os.listdir(configs_dir): if not config_name.endswith(".txt"): continue # 拼接完整配置文件路径 full_config_path = os.path.join(configs_dir, config_name) parse = CiscoConfParse(full_config_path) # 提取所有接口对象 intf_objects = parse.find_objects(r'^interface') for intf_obj in intf_objects: # 筛选access模式接口 if intf_obj.re_search_children(r'switchport mode access'): # 检查是否存在dot1x认证配置 if intf_obj.re_search_children(r'dot1x pae authenticator'): intf_name = intf_obj.text.strip() print(f"符合条件的接口:{intf_name}(来自设备:{config_name})") # 可根据需求写入CSV文件,示例如下 with open(result_path, 'a', newline='', encoding='utf-8') as f: writer = csv.writer(f) # 按你实际需要的字段填充值,这里示例写入设备名和接口名到对应位置 writer.writerow([config_name, '', '', '', '', '', f"接口{intf_name}配置了access模式和dot1x认证"]) if __name__ == "__main__": check_services()
优化说明
- 直接调用
CiscoConfParse内置的find_objects和re_search_children方法,不需要手动写正则遍历行,适配思科配置的层级结构,逻辑更清晰 - 自动关联接口对象和子行配置,直接提取接口名称,完全匹配需求
- 补全了路径拼接逻辑,避免文件读取错误
内容的提问来源于stack exchange,提问作者CBLT
相关产品推荐
相关产品推荐

