CiscoConfParse打开部分Cisco配置文件报FATAL文件不存在错误求助
问题原因
你的报错核心是文件路径拼接错误:
os.listdir(configs)仅返回目标文件夹下的纯文件名,不会携带父级目录路径- 你直接将纯文件名传入
CiscoConfParse(config)时,Python会默认从脚本当前运行的工作目录查找文件,当工作目录和配置文件存放的Data文件夹不一致时,就会触发找不到文件的报错 - 你观察到部分文件可正常读取,属于巧合场景:要么是你曾经把对应文件放到过脚本运行目录,要么是某次运行时临时切换过工作目录刚好匹配
修复方案
只需要把传入CiscoConfParse的参数替换为拼接后的完整路径即可,修复后代码如下:
import os import re import csv from ciscoconfparse import CiscoConfParse def check_vlan1_ports(): # 配置文件存放目录 configs_dir = r'C:\Documents\Tutorials\Python\Scripts\NetworkAudit\Data' # 结果文件路径 result_path = r'c:\documents\result.csv' Header = ['Device', 'Rule', 'Exception', 'Status', 'Code', 'Severity', 'Reason'] # 一次性打开CSV文件写入,避免频繁开闭 with open(result_path, 'a', newline='', encoding='utf-8') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=Header) # 仅当文件为空时写入表头,避免重复表头 if os.path.getsize(result_path) == 0: writer.writeheader() # 遍历所有配置文件 for filename in os.listdir(configs_dir): if not filename.endswith(".txt"): continue # 拼接完整文件路径 full_file_path = os.path.join(configs_dir, filename) # 传入完整路径实例化CiscoConfParse parse = CiscoConfParse(full_file_path) vlan1 = parse.find_objects(r"^1\s+default.*") str_vlan1 = str(vlan1) vlan1_ports = re.findall(r'(Gi\d{1,3}\/\d{1,3})|(Fa\d{1,3}\/\d{1,3})', str_vlan1) if vlan1_ports: writer.writerow({ 'Device': filename, 'Rule': 1, 'Exception': 'Check Vlan1 ports', 'Status': 'Failed', 'Code': '1', 'Severity': 'High', 'Reason': vlan1_ports }) else: writer.writerow({ 'Device': filename, 'Rule': 1, 'Exception': 'Check Vlan1 ports', 'Status': 'Pass', 'Code': '1', 'Severity': 'High', 'Reason': 'No ports in vlan1' }) check_vlan1_ports()
额外优化点
- 把CSV文件的打开逻辑移到循环外,避免每次写入数据都频繁开闭文件,大幅提升运行效率
- 增加了表头写入判断,只有结果文件为空时才写入表头,避免多次运行脚本产生重复表头
- 增加了编码参数指定为
utf-8,避免文件名或配置内容含中文时出现乱码
内容的提问来源于stack exchange,提问作者CBLT
相关产品推荐
相关产品推荐

