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

Python2.7.5解析路由器接口输出文本导出Excel表技术求助

路由器接口日志转Excel实现方案

1. 依赖安装

Python2.7环境下使用xlwt生成Excel文件,执行如下命令安装兼容版本:
pip install xlwt==1.3.0

2. 实现脚本

# -*- coding: utf-8 -*-
import xlwt

def parse_router_log(log_path, output_excel_path):
    # 存储解析后的所有接口数据
    result = []
    current_hostname = ''
    
    with open(log_path, 'r') as f:
        for line in f:
            line = line.strip()
            # 跳过空行
            if not line:
                continue
            # 跳过分隔符行
            if line.startswith('#'):
                continue
            # 提取当前设备主机名
            if line.startswith('hostname '):
                current_hostname = line.split('hostname ')[1].strip()
                continue
            # 跳过接口表头行
            if line.startswith('Interface'):
                continue
            # 解析接口数据行
            parts = line.split()
            if len(parts) < 6:
                continue
            interface = parts[0]
            ip_addr = parts[1]
            ok_flag = parts[2]
            method = parts[3]
            protocol = parts[-1]
            status = ' '.join(parts[4:-1])
            # 组装单条数据加入结果集
            result.append([
                current_hostname,
                interface,
                ip_addr,
                ok_flag,
                method,
                status,
                protocol
            ])
    
    # 写入Excel文件
    workbook = xlwt.Workbook(encoding='utf-8')
    sheet = workbook.add_sheet('接口信息')
    # 写入表头
    headers = ['Hostname', 'Interface', 'IP Address', 'OK?', 'Method', 'Status', 'Protocol']
    for col_idx, header in enumerate(headers):
        sheet.write(0, col_idx, header)
    # 写入业务数据
    for row_idx, row_data in enumerate(result, start=1):
        for col_idx, cell_data in enumerate(row_data):
            sheet.write(row_idx, col_idx, cell_data)
    # 保存文件
    workbook.save(output_excel_path)
    print "解析完成,结果已保存至:%s" % output_excel_path

if __name__ == '__main__':
    # 可根据实际路径修改日志文件和输出文件路径
    LOG_FILE = 'router_log.txt'
    OUTPUT_FILE = 'router_interface.xls'
    parse_router_log(LOG_FILE, OUTPUT_FILE)

3. 使用方法

  1. 将所有路由器的命令输出内容保存为文本文件,命名为router_log.txt,和脚本放在同一目录下
  2. 执行脚本:python parse_router.py
  3. 执行完成后同目录下会生成router_interface.xls文件,完全符合要求的表头和数据格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:15:00