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

如何用Netmiko解析Cisco交换机TDR数据并有序导入Excel

解决Cisco TDR诊断数据有序导入Excel的方案

核心思路

Netmiko的use_textfsm=True参数会自动将交换机的文本输出转换为结构化的字典列表,这是实现有序导入Excel的关键——无需手动解析杂乱的文本,直接用数据处理工具生成规范的Excel文件。

步骤1:安装必要依赖

执行以下命令安装数据处理和Excel操作库:

pip install pandas openpyxl

步骤2:修改代码实现导出

替换原代码,添加结构化数据处理和Excel导出逻辑:

from netmiko import ConnectHandler
import pandas as pd

# 设备凭证
ip = "192.168.xx.xx"
username = "admin"
password = "pass"
pass_enable = "secret"
DEVICE_TYPE = 'cisco_ios'

# 建立设备连接
conexion = ConnectHandler(ip=ip, username=username, password=password, secret=pass_enable, device_type=DEVICE_TYPE)
if not conexion.check_enable_mode():
    conexion.enable()

# 获取结构化TDR诊断数据
tdr_structured = conexion.send_command('show cable-diagnostics tdr interface Gi1/0/1', use_textfsm=True)

# 提取TDR测试时间(补充完整诊断信息)
raw_output = conexion.send_command('show cable-diagnostics tdr interface Gi1/0/1')
test_run_time = [line.split(': ', 1)[1] for line in raw_output.split('\n') if 'TDR test last run on:' in line][0]

# 为每条配对数据添加测试时间字段
for pair_data in tdr_structured:
    pair_data['test_run_time'] = test_run_time

# 转换为DataFrame并导出到Excel
df = pd.DataFrame(tdr_structured)
df.to_excel('cisco_tdr_diagnostics.xlsx', index=False, engine='openpyxl')

print("TDR诊断数据已成功导出到cisco_tdr_diagnostics.xlsx")

代码说明

  • 结构化数据处理:use_textfsm=True返回的字典列表包含interface、speed、local_pair等字段,每个字典对应一对线缆的诊断结果
  • 补充测试时间:从原始输出中提取测试时间,添加到每条数据中,保留完整的诊断上下文
  • Excel导出:pandas的DataFrame.to_excel()方法自动将结构化数据转换为规范的Excel表格,保证列对齐和数据有序
  • 参数说明:index=False避免导出无意义的索引列,engine='openpyxl'支持生成xlsx格式文件

扩展:多接口批量导出

如果需要诊断多个接口,可通过循环接口列表收集数据后统一导出:

# 示例:批量处理多个接口
interfaces = ['Gi1/0/1', 'Gi1/0/2', 'Gi1/0/3']
all_tdr_data = []

for intf in interfaces:
    tdr_data = conexion.send_command(f'show cable-diagnostics tdr interface {intf}', use_textfsm=True)
    raw_out = conexion.send_command(f'show cable-diagnostics tdr interface {intf}')
    test_time = [line.split(': ', 1)[1] for line in raw_out.split('\n') if 'TDR test last run on:' in line][0]
    for entry in tdr_data:
        entry['test_run_time'] = test_time
        all_tdr_data.append(entry)

# 导出所有接口数据
pd.DataFrame(all_tdr_data).to_excel('multi_interface_tdr.xlsx', index=False, engine='openpyxl')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:40:34