Python提取txt文件中SNMP网卡接口指定有效行的实现方法
SNMP导出网卡信息清理代码调整方案
核心处理逻辑
- 合并拆分记录:SNMP导出的ifDescr条目默认第一行存OID+索引,第二行存接口名称,逐行扫描时暂存OID行,和下一行的接口名称拼接即可恢复完整单条记录
- 过滤冗余条目:建立关键字黑名单,排除名称包含WFP、QoS、Filter、Miniport、虚拟等系统附加服务/虚拟接口的条目,仅保留物理网卡原生条目
Python示例代码(可直接适配其他语言逻辑)
# 配置项 input_path = "你的原始SNMP导出文件.txt" output_path = "清理后物理网卡列表.txt" # 冗余条目关键字黑名单,可根据实际导出内容补充 filter_blacklist = {"WFP", "QoS", "过滤", "Filter", "Virtual", "虚拟", "Miniport", "WAN"} # 处理逻辑 temp_oid_line = "" clean_result = [] with open(input_path, "r", encoding="utf-8") as f: for current_line in f: current_line = current_line.strip() if not current_line: continue # 识别OID行(ifDescr对应的OID前缀可根据你的导出格式调整) if current_line.startswith((".1.3.6.1.2.1.2.2.1.2", "interfaces.ifTable.ifEntry.ifDescr")): temp_oid_line = current_line continue # 拼接为完整单条记录 full_entry = f"{temp_oid_line} {current_line}" # 过滤冗余条目 if not any(keyword in current_line for keyword in filter_blacklist): clean_result.append(full_entry) temp_oid_line = "" # 输出结果 with open(output_path, "w", encoding="utf-8") as f: f.write("\n".join(clean_result))
适配说明
如果你的原始代码是其他语言,直接复用以下逻辑即可:
- 逐行读取原始文件,跳过空行
- 识别OID行暂存,将下一行内容和暂存的OID行拼接为完整记录
- 用黑名单匹配接口名称,过滤不符合要求的虚拟/附加服务条目
- 输出所有符合要求的记录到新文件
内容的提问来源于stack exchange,提问作者Lu儒
相关产品推荐
相关产品推荐

