以下是一个批量备份交换机配置的脚本示例:

import paramiko
import time

# 定义交换机列表
switches = [
    {
        'host': '192.168.1.1',
        'username': 'admin',
        'password': 'password',
        'enable_password': 'enable_password',
        'output_file': 'switch1_config.txt'
    },
    {
        'host': '192.168.1.2',
        'username': 'admin',
        'password': 'password',
        'enable_password': 'enable_password',
        'output_file': 'switch2_config.txt'
    },
    # 添加更多交换机...
]

# 配置SSH连接参数
ssh_params = paramiko.SSHClient()
ssh_params.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 遍历交换机列表
for switch in switches:
    host = switch['host']
    username = switch['username']
    password = switch['password']
    enable_password = switch['enable_password']
    output_file = switch['output_file']

    try:
        # SSH连接交换机
        ssh_params.connect(host, username=username, password=password)
        ssh_shell = ssh_params.invoke_shell()

        # 输入enable密码
        ssh_shell.send('enable\n')
        time.sleep(1)
        ssh_shell.send(enable_password + '\n')
        time.sleep(1)

        # 发送备份配置命令
        ssh_shell.send('terminal length 0\n')
        time.sleep(1)
        ssh_shell.send('show running-config\n')
        time.sleep(5)

        # 读取交换机配置输出
        output = ssh_shell.recv(65535).decode()

        # 将配置保存到文件
        with open(output_file, 'w') as file:
            file.write(output)

        print(f"成功备份交换机 {host} 的配置到文件 {output_file}")

    except paramiko.AuthenticationException:
        print(f"交换机 {host} 的认证失败")
    except paramiko.SSHException as e:
        print(f"SSH连接错误:{str(e)}")
    except Exception as e:
        print(f"备份交换机配置时发生错误:{str(e)}")

    finally:
        # 关闭SSH连接
        ssh_params.close()

请注意,这只是一个示例脚本,并不包含所有可能的情况和错误处理。在使用脚本之前,请确保已经安装了 Paramiko 库,并根据实际情况修改交换机列表以及 SSH 连接参数。此外,还可以根据需要添加其他错误处理和日志记录等功能。

Python 批量备份交换机配置脚本

原文地址: https://www.cveoy.top/t/topic/pllQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录