NAPALM 网络自动化框架教程

NAPALM(Network Automation and Programmability Abstraction Layer with Multivendor support)是一个 Python 库,为多厂商网络设备提供统一的 API 接口。无论你管理的是 Cisco、Juniper、Arista 还是其他品牌的设备,NAPALM 都提供相同的方法来获取设备信息、推送配置和进行配置回滚。NAPALM 可以独立使用,也可以作为 Ansible 或 Salt 的底层驱动集成到自动化工作流中。

一、安装 NAPALM

pip3 install napalm

# 安装特定驱动
pip3 install napalm-ios napalm-junos napalm-eos napalm-nxos

# 验证安装
python3 -c "import napalm; print(napalm.__version__)"

二、基本使用

2.1 连接设备并获取信息

#!/usr/bin/env python3
from napalm import get_network_driver

# 选择设备驱动
driver = get_network_driver("ios")

# 建立连接
device = driver(
    hostname="192.168.1.1",
    username="admin",
    password="password",
    optional_args={"secret": "enable_password"}
)

device.open()

# 获取设备基本信息
facts = device.get_facts()
print(f"主机名: {facts['hostname']}")
print(f"型号: {facts['model']}")
print(f"系统版本: {facts['os_version']}")
print(f"运行时间: {facts['uptime']} 秒")
print(f"序列号: {facts['serial_number']}")

device.close()

2.2 获取接口信息

device.open()

# 接口列表和状态
interfaces = device.get_interfaces()
for name, info in interfaces.items():
    status = "UP" if info["is_up"] else "DOWN"
    print(f"{name}: {status} - {info['description']}")

# 接口 IP 地址
ip_addresses = device.get_interfaces_ip()
for intf, ips in ip_addresses.items():
    for version, addrs in ips.items():
        for addr, prefix in addrs.items():
            print(f"{intf}: {addr}/{prefix['prefix_length']}")

# 接口计数器
counters = device.get_interfaces_counters()

device.close()

三、配置管理

3.1 配置替换(Replace)

device.open()

# 加载完整配置文件(替换模式)
device.load_replace_candidate(filename="new_config.cfg")

# 查看配置差异
diff = device.compare_config()
print(diff)

# 如果差异正确,提交配置
if diff:
    device.commit_config()
    print("配置已提交")
else:
    device.discard_config()
    print("无配置变更")

device.close()

3.2 配置合并(Merge)

device.open()

# 加载增量配置(合并模式)
config_snippet = """
interface GigabitEthernet0/1
 description Uplink to Core Switch
 ip address 10.0.1.1 255.255.255.0
 no shutdown
"""
device.load_merge_candidate(config=config_snippet)

# 查看差异并提交
diff = device.compare_config()
print(f"配置差异:
{diff}")

device.commit_config()
device.close()

3.3 配置回滚

device.open()

# 回滚到上一次的配置
device.rollback()
print("配置已回滚")

device.close()

四、网络状态查询

device.open()

# BGP 邻居信息
bgp_neighbors = device.get_bgp_neighbors()

# 路由表
routing_table = device.get_route_to(destination="10.0.0.0/24")

# ARP 表
arp_table = device.get_arp_table()

# LLDP 邻居
lldp_neighbors = device.get_lldp_neighbors()

# 环境信息(温度、风扇、电源)
environment = device.get_environment()

# NTP 服务器
ntp_servers = device.get_ntp_servers()

# MAC 地址表
mac_table = device.get_mac_address_table()

device.close()

五、批量管理脚本

#!/usr/bin/env python3
import json
from napalm import get_network_driver

devices = [
    {"hostname": "192.168.1.1", "driver": "ios", "username": "admin", "password": "pass1"},
    {"hostname": "192.168.1.2", "driver": "junos", "username": "admin", "password": "pass2"},
    {"hostname": "192.168.1.3", "driver": "eos", "username": "admin", "password": "pass3"},
]

for dev_info in devices:
    driver = get_network_driver(dev_info["driver"])
    device = driver(
        hostname=dev_info["hostname"],
        username=dev_info["username"],
        password=dev_info["password"],
    )
    try:
        device.open()
        facts = device.get_facts()
        print(f"[{facts['hostname']}] {facts['model']} - {facts['os_version']}")
        device.close()
    except Exception as e:
        print(f"[{dev_info['hostname']}] 连接失败: {e}")

六、与 Ansible 集成

# 安装 NAPALM Ansible 模块
pip3 install napalm-ansible

# Playbook 示例
cat > napalm_playbook.yml << 'EOF'
---
- name: 使用 NAPALM 管理网络设备
  hosts: routers
  connection: local
  tasks:
    - name: 获取设备信息
      napalm_get_facts:
        hostname: "{{ ansible_host }}"
        username: "{{ ansible_user }}"
        password: "{{ ansible_password }}"
        dev_os: "{{ napalm_driver }}"
        filter: ["facts", "interfaces"]
      register: result

    - debug:
        var: result.ansible_facts.napalm_facts
EOF

总结

NAPALM 为多厂商网络设备提供了统一的自动化接口,使配置管理和状态查询变得简单一致。配合 Ansible 可以构建更强大的自动化流程,使用 Batfish 可以在推送前验证配置的正确性。选购搬瓦工 VPS 请参考 全部方案,购买时使用优惠码 NODESEEK2026 可享受 6.77% 的优惠,通过 bwh81.net 进入官网购买。

关于本站

搬瓦工VPS中文网(bwgvps.com)是非官方中文信息站,整理搬瓦工的方案、优惠和教程。我们不销售主机,不提供技术服务。

新手必读
搬瓦工优惠码

NODESEEK2026(优惠 6.77%)

购买时填入即可抵扣。