登录
首页 >  文章 >  python教程

Python脚本如何访问网络设备全解析

时间:2026-03-02 11:09:49 272浏览 收藏

本文深入解析了使用Python脚本自动化访问和管理网络设备的四大主流方法:以Netmiko库为代表的SSH高层封装(推荐入门与日常运维)、基于Paramiko的底层SSH精细控制、面向现代设备的REST API交互,以及支持多厂商统一操作的NAPALM抽象层;无论你是要快速配置Cisco交换机、批量查询华为路由器状态,还是构建跨厂商自动化平台,都能从中找到适配场景的技术选型依据与即用型代码示例。

怎么编写Python脚本访问网络设备?

编写Python脚本访问网络设备,通常用于自动化配置交换机、路由器或防火墙等设备。常见方式包括使用SSH、Telnet、REST API 或专用库(如Netmiko、NAPALM)来实现。下面介绍几种主流方法和示例。

1. 使用 Netmiko 库(推荐用于 SSH 访问)

Netmiko 是一个基于 Paramiko 的 Python 库,专门用于简化与网络设备的 SSH 通信。支持 Cisco、Huawei、Juniper、Arista 等主流厂商设备。

安装 Netmiko:

pip install netmiko

示例:登录 Cisco 设备并执行命令

from netmiko import ConnectHandler

# 定义设备信息
device = {
    'device_type': 'cisco_ios',      # 设备类型
    'host':   '192.168.1.1',        # 设备IP
    'username': 'admin',
    'password': 'password',
    'secret': 'enable_password',    # enable 密码(可选)
}

# 建立连接
connection = ConnectHandler(**device)

# 进入特权模式
connection.enable()

# 执行命令
output = connection.send_command('show ip interface brief')
print(output)

# 配置模式下修改配置
config_commands = ['interface loopback0', 'ip address 1.1.1.1 255.255.255.255']
connection.send_config_set(config_commands)

# 断开连接
connection.disconnect()

常见 device_type 值:

  • cisco_ios
  • cisco_nxos
  • cisco_asa
  • huawei
  • juniper_junos
  • arista_eos

2. 使用 Paramiko 手动实现 SSH

如果你需要更底层控制,可以使用 Paramiko 直接处理 SSH 连接。

安装 Paramiko:

pip install paramiko

import paramiko
import time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname='192.168.1.1',
           username='admin',
           password='password')

# 创建交互式 shell
shell = ssh.invoke_shell()
shell.send('terminal length 0\n')  # 防止分页
time.sleep(1)
shell.send('show version\n')
time.sleep(3)

# 读取输出
output = shell.recv(65535).decode('utf-8')
print(output)

shell.close()
ssh.close()

3. 使用 REST API(适用于支持 API 的设备)

现代网络设备(如 Cisco Catalyst 9k、华为 CloudEngine)通常提供 RESTful API 接口。

import requests
import json

url = "https://192.168.1.1/restconf/data/interfaces/interface=GigabitEthernet1"

headers = {
    'Accept': 'application/yang-data+json',
    'Content-Type': 'application/yang-data+json'
}

# 使用 HTTP Basic Auth
response = requests.get(url, headers=headers, auth=('admin', 'password'), verify=False)

# 注意:生产环境不要 use verify=False
if response.status_code == 200:
    print(json.dumps(response.json(), indent=2))
else:
    print(f"Error: {response.status_code}")

4. 使用 NAPALM(跨平台统一接口)

NAPALM(Network Automation and Programmability Abstraction Layer)支持多种厂商和多种操作(获取状态、合并配置等)。

安装:

pip install napalm

from napalm import get_network_driver

driver = get_network_driver('ios')  # cisco_ios
device = driver('192.168.1.1', 'admin', 'password')

device.open()
print(device.get_facts())           # 获取设备基本信息
print(device.get_interfaces())      # 获取接口信息

# 合并配置
device.load_merge_candidate(config="interface loopback1\n ip address 2.2.2.2 255.255.255.255")
print(device.compare_config())      # 查看差异
# device.commit_config()            # 提交更改(确认无误后启用)

device.close()

基本上就这些。选择哪种方式取决于你的设备类型、安全要求和自动化需求。Netmiko 最适合传统 CLI 操作,REST API 更适合现代设备,NAPALM 适合统一多厂商管理。

以上就是《Python脚本如何访问网络设备全解析》的详细内容,更多关于Python脚本,网络设备的资料请关注golang学习网公众号!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>