Netmiko:Python多厂商网络设备SSH自动化库

Netmiko 是一个基于 Paramiko 的 Python 库,专门用于简化网络设备的 SSH 管理。它支持 Cisco、Juniper、Arista、HP、华为、Fortinet 等 100+ 平台,提供统一的 API 接口,让网络工程师可以用一套代码管理不同厂商的设备。

安装

pip install netmiko

基本用法

建立 SSH 连接

from netmiko import ConnectHandler

device = {
    'device_type': 'cisco_xe',
    'host': '192.168.1.1',
    'username': 'admin',
    'password': 'password',
}

net_connect = ConnectHandler(**device)
print(net_connect.find_prompt())  # 输出: cisco5#

device_type 指定设备厂商和型号,常见值包括:

device_type厂商/平台
cisco_iosCisco IOS
cisco_xeCisco IOS XE
cisco_nxosCisco NX-OS
juniper_junosJuniper JunOS
arista_eosArista EOS
huawei华为
hp_comwareH3C Comware
fortinetFortinet

执行 show 命令

output = net_connect.send_command('show ip arp')
print(output)

Netmiko 会自动处理输出分页(terminal length 0),并去除命令回显和提示符,只返回纯净的命令输出。

对于耗时较长的命令,可以指定超时时间:

output = net_connect.send_command('show tech-support', delay_factor=5, max_loops=500)

执行配置命令

config_commands = [
    'interface GigabitEthernet0/1',
    'description Uplink-to-Core',
    'ip address 10.0.0.1 255.255.255.0',
    'no shutdown',
]

output = net_connect.send_config_set(config_commands)
print(output)

# 保存配置
net_connect.save_config()

send_config_set() 会自动进入配置模式、逐条执行命令、退出配置模式。

批量管理多台设备

from netmiko import ConnectHandler

devices = [
    {'device_type': 'cisco_xe', 'host': '192.168.1.1', 'username': 'admin', 'password': 'pass1'},
    {'device_type': 'cisco_xe', 'host': '192.168.1.2', 'username': 'admin', 'password': 'pass2'},
    {'device_type': 'cisco_xe', 'host': '192.168.1.3', 'username': 'admin', 'password': 'pass3'},
]

for device in devices:
    try:
        conn = ConnectHandler(**device)
        output = conn.send_command('show version')
        print(f'{device["host"]}: {output[:100]}...')
        conn.disconnect()
    except Exception as e:
        print(f'{device["host"]}: 连接失败 - {e}')

高级用法

使用配置文件管理设备信息

import yaml
from netmiko import ConnectHandler

with open('devices.yaml') as f:
    devices = yaml.safe_load(f)

for device in devices:
    conn = ConnectHandler(**device)
    conn.send_command('show running-config')
    conn.disconnect()

devices.yaml 示例:

- device_type: cisco_xe
  host: 192.168.1.1
  username: admin
  password: secret
- device_type: juniper_junos
  host: 192.168.1.2
  username: admin
  password: secret

配置回滚

# 备份当前配置
backup = net_connect.send_command('show running-config')

# 应用新配置
net_connect.send_config_set(new_config)

# 如果出错,回滚
net_connect.send_config_set(backup.split('\n'))

多线程批量操作

from concurrent.futures import ThreadPoolExecutor
from netmiko import ConnectHandler

def run_command(device, command):
    conn = ConnectHandler(**device)
    output = conn.send_command(command)
    conn.disconnect()
    return device['host'], output

with ThreadPoolExecutor(max_workers=10) as executor:
    futures = [executor.submit(run_command, d, 'show version') for d in devices]
    for future in futures:
        host, output = future.result()
        print(f'{host}: {output[:80]}...')

最佳实践

  1. 始终使用 try/except 处理连接异常:网络环境不稳定,设备可能不可达
  2. 使用配置文件管理设备信息:不要硬编码 IP 和密码
  3. 批量操作使用多线程:串行执行效率低,多线程可大幅提升速度
  4. 操作前备份配置:配置变更前先 show running-config 保存
  5. 合理设置超时参数:大设备或复杂命令需要增加 delay_factormax_loops
  6. 及时断开连接:操作完成后调用 disconnect() 释放资源

总结

Netmiko 是网络自动化的利器,用 Python 替代手工 SSH 登录设备执行命令,大幅提升运维效率。配合配置文件管理和多线程,可以轻松实现数百台设备的批量配置和巡检。