import paramiko
import os
from datetime import datetime
def export_switch_config(host, username, password, save_path):
try:
# 建立 SSH 连接
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print(f"正在连接到交换机 {host} ...")
ssh.connect(hostname=host, username=username, password=password, timeout=10)
# 打开交互式终端
shell = ssh.invoke_shell()
shell.send("terminal length 0\n") # 关闭分页显示
shell.send("show running-config\n") # 执行导出配置命令
shell.send("exit\n")
# 获取输出内容
output = ""
while True:
if shell.recv_ready():
output += shell.recv(65535).decode("utf-8")
else:
break
# 关闭 SSH 连接
ssh.close()
# 提取配置内容(去除无关信息)
config_lines = output.splitlines()
config = "\n".join(config_lines[2:-1]) # 适配不同交换机,调整索引
# 保存配置到文件
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
file_name = f"switch_config_{timestamp}.txt"
full_path = os.path.join(save_path, file_name)
with open(full_path, "w", encoding="utf-8") as file:
file.write(config)
print(f"配置已成功保存到: {full_path}")
except Exception as e:
print(f"发生错误: {e}")
if __name__ == "__main__":
# 用户输入交换机信息
host = input("请输入交换机IP地址: ")
username = input("请输入用户名: ")
password = input("请输入密码: ")
# 获取桌面路径
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
# 执行导出配置
export_switch_config(host, username, password, desktop_path)