以下是一个使用 Python 脚本批量备份交换机的示例,使用 Paramiko 库进行 SSH 连接和命令执行:

import paramiko
import time

# 定义交换机的IP地址、用户名和密码
switches = [
    {'ip': '192.168.1.1', 'username': 'admin', 'password': 'password1'},
    {'ip': '192.168.1.2', 'username': 'admin', 'password': 'password2'},
    {'ip': '192.168.1.3', 'username': 'admin', 'password': 'password3'}
]

# 配置备份保存的目录
backup_dir = '/path/to/backup/directory/'

# 配置 SSH 连接的端口号
ssh_port = 22

# 配置 SSH 连接的超时时间(秒)
ssh_timeout = 10

# 配置 SSH 连接的日志文件路径
ssh_logfile = '/path/to/ssh/logfile.txt'

def backup_switch(switch):
    try:
        # 创建 SSH 客户端对象
        client = paramiko.SSHClient()
        
        # 自动添加和保存交换机的 SSH 密钥
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        
        # 连接交换机
        client.connect(switch['ip'], port=ssh_port, username=switch['username'], password=switch['password'], timeout=ssh_timeout)
        
        # 执行命令
        stdin, stdout, stderr = client.exec_command('show running-config')
        
        # 获取命令输出
        output = stdout.read().decode('utf-8')
        
        # 生成备份文件名
        timestamp = time.strftime('%Y%m%d%H%M%S', time.localtime())
        backup_filename = f'{switch['ip']}_backup_{timestamp}.txt'
        
        # 保存备份文件
        with open(backup_dir + backup_filename, 'w') as file:
            file.write(output)
        
        print(f'Successfully backed up {switch['ip']} to {backup_filename}')
    except Exception as e:
        print(f'Failed to backup {switch['ip']}: {str(e)}')
    finally:
        # 关闭 SSH 连接
        client.close()

# 执行备份
for switch in switches:
    backup_switch(switch)

上述脚本使用 paramiko 库来进行 SSH 连接和命令执行。您需要在代码中替换实际的交换机 IP 地址、用户名和密码,以及备份保存的目录。执行脚本后,它将逐个连接到每个交换机并执行 'show running-config' 命令,然后将输出保存为备份文件。备份文件名包含了交换机的 IP 地址和时间戳。如果备份过程中出现任何错误,它将打印错误消息。


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

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