You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本遍历交换机接口采集信息存CSV的报错求助

问题排查与解决方案

一、先解决现有脚本的报错问题

1. NameError: regex_memory未定义

你要么没定义这个变量就直接调用,要么复制脚本时漏了对应的正则定义块。先在使用regex_memory的代码前完成定义:

import re
# 替换成你实际需要的正则表达式
regex_memory = re.compile(r'your_regex_pattern_here')

2. AttributeError: 'NoneType' object has no attribute 'group'

这是正则匹配无结果返回None,你却直接调用.group()导致的。Python里re.search()/re.match()没匹配到就返回None,和Java的匹配逻辑不同,必须先判断结果是否存在:

match_result = regex_memory.search(device_output)
if match_result:
    target_value = match_result.group(1)
else:
    # 匹配失败时赋值默认值,避免报错
    target_value = ""

3. IndexError: 列表索引越界

你访问列表元素的索引超过了列表实际长度。比如用.split()拆分文本后,直接取split_data[3]但列表只有2个元素。处理前先判断长度:

split_content = device_output.split()
if len(split_content) >= 4:
    target_value = split_content[3]
else:
    target_value = ""

二、接口信息采集逻辑实现

以Cisco交换机为例,通过show interfaces命令获取所需数据,其他厂商(华为、H3C等)需调整匹配规则适配输出格式:

import re

# 匹配Cisco接口状态与错误统计的正则(可根据实际输出微调)
interface_pattern = re.compile(
    r'^(\S+)\s+is\s+(\S+),.*?Giants\s+(\d+).*?CRC\s+(\d+).*?input errors\s+(\d+)',
    re.DOTALL | re.MULTILINE
)

# 假设已经通过SSH/Telnet获取到设备的show interfaces输出
device_output = get_device_output_via_ssh(device_ip)
interface_data = []

for match in interface_pattern.finditer(device_output):
    interface_info = {
        "设备IP": device_ip,
        "接口名称": match.group(1),
        "接口状态": match.group(2),
        "Giants计数": match.group(3),
        "CRC错误数": match.group(4),
        "输入错误数": match.group(5)
    }
    interface_data.append(interface_info)

三、导出数据到CSV

用Python自带的csv模块实现,无需额外安装依赖:

import csv

# 假设所有设备的接口数据都存在all_device_data列表中
csv_headers = ["设备IP", "接口名称", "接口状态", "Giants计数", "CRC错误数", "输入错误数"]

with open("交换机接口统计.csv", "w", encoding="utf-8-sig", newline="") as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=csv_headers)
    writer.writeheader()  # 写入表头
    writer.writerows(all_device_data)  # 批量写入所有数据

utf-8-sig编码是为了让Excel能正确识别中文,避免乱码。

内容的提问来源于stack exchange,提问作者Cootie_Cooter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:05:21