Python脚本备份华为交换机配置

要使用Python脚本备份华为交换机的配置,可以使用SSH协议与交换机建立连接,并执行命令来获取配置信息并保存到文件中。

import os
import paramiko

def save_config(hostname, username, password, backup_dir):
    try:
        # 建立SSH连接
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname, username=username, password=password)

        # 执行命令获取设备配置
        stdin, stdout, stderr = ssh.exec_command("display current-configuration")

        # 生成备份文件的路径和文件名
        filename = f"{hostname}_config.txt"
        backup_path = os.path.join(backup_dir, filename)

        # 保存配置到文件
        with open(backup_path, "w") as file:
            file.write(stdout.read().decode())

        print(f"设备{hostname}配置保存成功!")

    except paramiko.AuthenticationException:
        print(f"设备{hostname}认证失败,请检查用户名和密码。")
    except paramiko.SSHException as e:
        print(f"设备{hostname} SSH连接错误:", str(e))
    except Exception as e:
        print(f"设备{hostname}错误:", str(e))

    finally:
        if ssh:
            ssh.close()

# 从文本文件中读取设备清单
def read_device_list(file_path):
    with open(file_path, "r") as file:
        return [line.strip() for line in file.readlines()]

# 设备清单文件路径
device_list_file = "device_list.txt"
# 备份目录
backup_directory = "G:\config\switch\hs-26d"

# 登录信息
username = "admin"
password = "S**********7!@$"

# 读取设备清单
devices = read_device_list(device_list_file)

# 逐个保存设备配置
for hostname in devices:
    save_config(hostname, username, password, backup_directory)

device_list.txt

192.168.20.9

备份成功

Python脚本备份华为交换机配置_第1张图片

 文件夹可以看到备份文件

你可能感兴趣的:(python,华为,开发语言)