Netmiko

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}')