在中小型企业网络运维中,交换机配置备份是一项基础但极其重要的工作。传统的手工备份方式需要逐台登录设备执行命令,不仅效率低下,还容易遗漏关键设备。我曾参与过一个制造业客户的网络改造项目,他们拥有37台不同厂商的交换机,每次变更前都需要人工备份配置,运维团队每月要花费近20个工时在这项重复劳动上。
这个痛点催生了我们开发这款基于Python的网络拓扑图管理工具。它通过可视化拓扑图界面集中管理设备,并实现一键批量备份功能。核心解决三个问题:
工具采用三层架构:
code复制[GUI层] PyQt5拓扑图界面
↓
[业务层] 设备管理/备份引擎
↓
[通信层] Paramiko(SSH)/Telnet库
选择PyQt5而非Web方案的原因:
不同厂商设备需适配不同协议:
python复制def get_connection(device):
if device.vendor == "Huawei":
return HuaweiSSH(device.ip, device.credential)
elif device.vendor == "Cisco":
return CiscoTelnet(device.ip, device.credential)
# 其他厂商适配...
注意:华为较新设备默认关闭Telnet,建议统一使用SSH协议。思科老设备可能需要开启
service telnet-zeroidle
完整备份流程包含以下步骤:
关键代码示例:
python复制def backup_switch(switch):
try:
with connect(switch) as conn:
# 华为使用display current-configuration
# 思科使用show running-config
config = conn.exec_command(switch.backup_cmd)
save_to_file(switch.name, config)
return True
except Exception as e:
log_error(f"Backup failed for {switch.ip}: {str(e)}")
return False
采用Git式版本控制方案:
code复制backups/
├── SW1/
│ ├── 20240501_1200.cfg
│ ├── 20240502_0900.cfg
│ └── diff_20240501-20240502.patch
└── SW2/
└── ...
差异对比使用difflib库:
python复制def compare_configs(old, new):
diff = difflib.unified_diff(
old.splitlines(),
new.splitlines(),
fromfile='old',
tofile='new'
)
return '\n'.join(diff)
| 错误现象 | 可能原因 | 解决方案 |
|---|---|---|
| Connection timeout | 防火墙拦截/设备繁忙 | 调整TCP超时为30秒 |
| Authentication failed | 特权密码未配置 | 检查enable密码设置 |
| Command not found | 厂商命令差异 | 更新设备命令映射表 |
通过LLDP协议自动构建拓扑图:
python复制def discover_topology(start_ip):
neighbors = {}
queue = [start_ip]
while queue:
current = queue.pop()
lldp_info = get_lldp_neighbors(current)
neighbors[current] = lldp_info
queue.extend(n for n in lldp_info if n not in neighbors)
return neighbors
预置常见合规规则:
实现示例:
python复制def check_compliance(config):
violations = []
if "snmp-server community public RO" in config:
violations.append("SNMP弱口令风险")
if "enable password 123456" in config:
violations.append("特权密码强度不足")
return violations
实际部署时需要注意:
我在某物流园区项目中验证的效果: