我管理了约1000台交换机,如果单台手工备份,那么工作量不可想像,由于客户的交换机不允许在上面做配置,所以使用了这个Python小程序,它可以帮助我们远程进行交换机的配置,原理很简单,就是通过sh run或者dis cur把交换机的当前运行配置给显示出来,再粘贴到以IP地址为名称的文本文件中。以下是代码:
import paramiko
import time
def backup_switch_config(ip, username, password, enable_password):
try:
# SSH连接
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(ip, username=username, password=password)
# 打开交互式shell
ssh_shell = ssh_client.invoke_shell()
# 登录
ssh_shell.send("enable\n")
ssh_shell.send(enable_password + "\n")
time.sleep(1) # 等待特权模式切换
# 发送命令
ssh_shell.send("terminal length 0\n") # 禁用分页显示
ssh_shell.send("sh cur\n")