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

如何用Python构造循环并将Netmiko命令输出分写入对应文件

修改Netmiko脚本实现命令输出分文件存储

以下是调整后的脚本,能够将show system的输出单独写入output1.txt,show run的输出写入output2.txt:

from netmiko import ConnectHandler

# 读取hosts.txt设备列表(每行格式:IP,用户名,密码,设备类型)
with open('hosts.txt', 'r') as hosts_file:
    # 过滤空行并拆分每行的设备信息
    hosts = [line.strip().split(',') for line in hosts_file if line.strip()]

# 遍历所有设备执行命令
for host in hosts:
    device_config = {
        'device_type': host[3],
        'ip': host[0],
        'username': host[1],
        'password': host[2],
    }

    try:
        # 建立设备连接
        connection = ConnectHandler(**device_config)
        print(f"已连接到设备 {host[0]}")

        # 执行show system并写入output1.txt
        system_output = connection.send_command('show system')
        with open('output1.txt', 'a', encoding='utf-8') as out1:
            out1.write(f"===== 设备 {host[0]} show system 输出 =====\n")
            out1.write(system_output)
            out1.write("\n\n")

        # 执行show run并写入output2.txt
        run_output = connection.send_command('show run')
        with open('output2.txt', 'a', encoding='utf-8') as out2:
            out2.write(f"===== 设备 {host[0]} show run 输出 =====\n")
            out2.write(run_output)
            out2.write("\n\n")

        # 断开连接
        connection.disconnect()
        print(f"已断开与设备 {host[0]} 的连接")

    except Exception as err:
        print(f"处理设备 {host[0]} 时发生错误: {str(err)}")

关键调整说明

  • 拆分了命令执行与文件写入的逻辑,每个命令对应独立的文件操作
  • 使用a(追加)模式打开文件,确保多设备的输出不会互相覆盖
  • 为每个设备的输出添加了分隔标题,方便后续区分不同设备的结果
  • 增加了encoding='utf-8'参数,避免部分设备输出包含特殊字符时出现编码错误
  • 保留异常处理逻辑,确保单个设备连接失败不会导致整个脚本终止

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:25:26