本文目录导读:

是的,实用脚本可以批量处理路由,具体实现方式取决于你使用的场景和工具,以下是几种常见的批量路由处理方案:
网络设备批量配置(如路由器、交换机)
使用 Python + Netmiko/Paramiko
from netmiko import ConnectHandler
devices = [
{'device_type': 'cisco_ios', 'host': '192.168.1.1', 'username': 'admin', 'password': 'pass'},
{'device_type': 'huawei', 'host': '192.168.1.2', 'username': 'admin', 'password': 'pass'}
]
routes = [
'ip route 10.0.1.0 255.255.255.0 192.168.2.1',
'ip route 10.0.2.0 255.255.255.0 192.168.3.1'
]
for device in devices:
net_connect = ConnectHandler(**device)
net_connect.enable()
for route in routes:
net_connect.send_config_set(route)
net_connect.save_config()
net_connect.disconnect()
使用 Ansible(批量自动化)
- name: 批量添加路由
hosts: routers
tasks:
- name: 添加静态路由
cisco.ios.ios_static_routes:
config:
- vrf: default
address_families:
- afi: ipv4
routes:
- dest: "10.0.1.0/24"
next_hops:
- forward_router_address: "192.168.2.1"
Linux 系统批量路由
Bash 脚本批量添加路由
#!/bin/bash
# 从文件读取路由
while IFS=' ' read -r network gateway interface; do
ip route add $network via $gateway dev $interface
done < routes.txt
# routes.txt 示例内容
# 10.0.1.0/24 192.168.1.1 eth0
# 10.0.2.0/24 192.168.1.2 eth0
批量删除路由
#!/bin/bash
# 删除所有特定网关的路由
for route in $(ip route show via 192.168.1.1 | awk '{print $1}'); do
ip route del $route via 192.168.1.1
done
Web 服务器/负载均衡路由
Nginx 批量配置路由
-- 使用 OpenResty 或 Lua 脚本
local routes = {
{"/api/v1/*", "http://backend1:8080"},
{"/api/v2/*", "http://backend2:8080"},
{"/api/v3/*", "http://backend3:8080"}
}
for _, route in ipairs(routes) do
ngx.location.capture("/route_config", {
method = ngx.HTTP_POST,
body = "path=" .. route[1] .. "&upstream=" .. route[2]
})
end
数据库/消息队列路由
批量路由配置示例
# 批量注册消息队列路由
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
routes = [
{'routing_key': 'order.create', 'queue': 'order_queue'},
{'routing_key': 'payment.success', 'queue': 'payment_queue'},
{'routing_key': 'user.register', 'queue': 'user_queue'}
]
for route in routes:
channel.queue_bind(
exchange='direct_exchange',
queue=route['queue'],
routing_key=route['routing_key']
)
推荐工具对比
| 工具/脚本 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
| Netmiko | 网络设备批量配置 | 支持多种厂商,易编程 | 需 Python 基础 |
| Ansible | 大规模自动化 | 无需代理,幂等性 | 学习曲线较陡 |
| Bash+iproute | Linux 系统 | 轻量,原生支持 | 功能有限 |
| Expect | 老旧设备 | 支持交互式 CLI | 脚本难维护 |
最佳实践建议
- 先测试后批量:在单个设备上测试脚本
- 错误处理:添加回滚机制
- 日志记录:记录每步操作
- 配置文件化:将路由保存在外部文件
示例:带错误处理的批量脚本框架
def batch_routes(device_list, route_file):
success = []
failed = []
with open(route_file) as f:
routes = f.readlines()
for device in device_list:
try:
conn = connect_device(device)
for route in routes:
apply_route(conn, route.strip())
success.append(device['host'])
except Exception as e:
failed.append({'device': device['host'], 'error': str(e)})
rollback(device) # 回滚
return {'success': success, 'failed': failed}
需要我针对你的具体场景(如路由器型号、操作系统、路由数量等)提供更详细的脚本示例吗?