本帖最后由 hoochanlon 于 2024-11-21 15:37 编辑
单个与批量交换机配置备份
单个备份
设计思路(五个关键):
- 连接 ssh 登录到交换机
- 通过
dis cu (display current-configuration)显示交换机配置
- 利用标识符“ops”、“return”作为读取的结尾。
- 读取内容到指定文本文件。
- 通过ftp导出vrpcfg.cfg文件进行对比,利用正则剔除
dis cu 之前的以上所有信息,保留 dis cu 输出的以下所有信息。
其他(todo & think):写出这些,以后剩下的的配置之类的,也差不多。
源码如下及地址:
import paramiko
import time
import os
from datetime import datetime
import re
hostname = "192.168.1.250"
username = "yonghuming"
password = "Mima12345@"
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
current_date = datetime.now().strftime("%Y%m%d")
backup_filename = f"switch_backup_{timestamp}.cfg"
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
date_folder_path = os.path.join(desktop_path, current_date)
backup_filepath = os.path.join(date_folder_path, backup_filename)
if not os.path.exists(date_folder_path):
os.makedirs(date_folder_path)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, username=username, password=password)
shell = client.invoke_shell()
shell.send("screen-length 0 temporary\n")
time.sleep(1)
shell.send("display current-configuration\n")
time.sleep(2)
output = ""
found_ops = False
while True:
part = shell.recv(8848).decode('utf-8')
output += part
if 'return' in part:
found_ops = True
if found_ops and 'return' in part:
break
with open(backup_filepath, "w") as backup_file:
backup_file.write(output)
with open(backup_filepath, "r") as backup_file:
raw_content = backup_file.read()
cleaned_output = re.sub(
r"(?s).*?display current-configuration\n",
"",
raw_content
)
with open(backup_filepath, "w") as backup_file:
backup_file.write(cleaned_output)
print(f"备份已完成,配置已保存到 {backup_filepath}")
except Exception as e:
print(f"连接或备份过程中发生错误: {e}")
finally:
client.close()
单个备份效果

批量备份
设计思路:
SSH内容如下

附源码地址:
import paramiko
import time
import os
import csv
from datetime import datetime
import re
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
current_date = datetime.now().strftime("%Y%m%d")
date_folder_path = os.path.join(desktop_path, current_date)
if not os.path.exists(date_folder_path):
os.makedirs(date_folder_path)
csv_file_path = os.path.join(desktop_path, "SSH登记表.csv")
try:
with open(csv_file_path, "r", encoding="utf-8") as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
if len(row) < 5:
print(f"跳过格式不正确的行: {row}")
continue
device_name, hostname, username, password, port = row
port = int(port)
backup_filename = f"{device_name}.txt"
backup_filepath = os.path.join(date_folder_path, backup_filename)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
print(f"正在连接到 {hostname} ({device_name}),端口 {port}...")
client.connect(hostname, username=username, password=password, port=port)
shell = client.invoke_shell()
shell.send("screen-length 0 temporary\n")
time.sleep(1)
shell.send("display current-configuration\n")
time.sleep(2)
output = ""
found_ops = False
while True:
part = shell.recv(8848).decode('utf-8')
output += part
if 'return' in part:
found_ops = True
if found_ops and 'return' in part:
break
with open(backup_filepath, "w", encoding="utf-8") as backup_file:
backup_file.write(output)
with open(backup_filepath, "r", encoding="utf-8") as backup_file:
raw_content = backup_file.read()
cleaned_output = re.sub(
r"(?s).*?display current-configuration\n",
"",
raw_content
)
with open(backup_filepath, "w", encoding="utf-8") as backup_file:
backup_file.write(cleaned_output)
print(f"{device_name} ({hostname}) 备份完成,保存到 {backup_filepath}")
except Exception as e:
print(f"备份 {device_name} ({hostname}) 失败: {e}")
finally:
client.close()
except FileNotFoundError:
print(f"CSV 文件未找到,请确认路径是否正确: {csv_file_path}")
except Exception as e:
print(f"处理 CSV 文件时发生错误: {e}")
单个备份与批量备份的效果一览


|