【问题标题】:Save startup-configuration from switchs/routers cisco with python script?使用 python 脚本从交换机/路由器 cisco 保存启动配置?
【发布时间】:2020-01-23 22:58:07
【问题描述】:

我想自动备份我的交换机/路由器配置 cisco。

我尝试创建这个脚本:

#!/usr/bin/env python3
#-*- conding: utf-8 -*-

from netmiko import ConnectHandler

cisco_test = {
    'device_type': 'cisco_ios',
    'host': 'xxx.xxx.xxx.xxx',
    'username': 'xxxxxx',
    'password': 'xxxxxxxxxx',
    'secret': 'xxxxxxx',
    }

net_connect = ConnectHandler(**cisco_test)
net_connect.enable()

config_commands = ['copy start tftp://xxx.xxx.xxx.xxx/test.bin']

output = net_connect.send_config_set(config_commands)

print(output)
net_connect.exit_enable_mode()

但它不起作用......你能告诉我怎么做吗?

【问题讨论】:

    标签: python cisco netmiko


    【解决方案1】:

    您将它们作为“配置命令”发送。在 IOS 中,必须从 Privileged EXEC 模式复制到 TFTP 服务器。如果从全局配置中执行,该命令将不起作用,除非它前面带有“do”,如do copy start tftp://...

    您是否尝试将启动配置备份到 TFTP 服务器?顺便说一句,将配置命名为“test.bin”的有趣选择。

    您可以通过两种方式做到这一点:

    1. 通过 TFTP 备份到设备,就像您正在做的那样
    2. 通过捕获“show run”命令的输出备份到文件

    第二个选项很酷:即使您的设备无法访问 TFTP 服务器,您仍然可以备份配置。

    方法一

    您不仅需要发送复制命令,还需要响应收到的提示:

    CISCO2921-K9#copy start tftp://10.122.151.118/cisco2921-k9-backup
    Address or name of remote host [10.122.151.118]? 
    Destination filename [cisco2921-k9-backup]? 
    !!
    1759 bytes copied in 0.064 secs (27484 bytes/sec)
    
    CISCO2921-K9#
    

    所以你必须准备好对这两个问题都用“Enter”回答

    这是一个工作脚本的示例:

    from netmiko import ConnectHandler
    
    # enter the IP for your TFTP server here
    TFTP_SERVER = "10.1.1.1"
    
    # to add a device, define its connection details below, then add its name 
    # to the list of "my_devices"
    device1 = {
        'device_type': 'cisco_ios',
        'host': '10.1.1.1',
        'username': 'admin',
        'password': 'cisco123',
        'secret': 'cisco123',
    }
    
    device2 = {
        'device_type': 'cisco_xr',
        'host': '10.1.1.2',
        'username': 'admin',
        'password': 'cisco123',
        'secret': 'cisco123',
    }
    
    # make sure you add every device above to this list
    my_devices = [device1, device2]
    
    # This is where the action happens. Connect, backup, respond to prompts
    # Feel free to change the date on the backup file name below, 
    # everything else should stay the same
    i = 0
    for device in my_devices:
        i += 1
        name = f"device{str(i)}"
        net_connect = ConnectHandler(**device)
        net_connect.enable()
        copy_command = f"copy start tftp://{TFTP_SERVER}/{name}-backup-02-26-2020"
    
        output = net_connect.send_command_timing(copy_command)
        if "Address or name" in output:
            output += net_connect.send_command_timing("\n")
        if "Destination filename" in output:
            output += net_connect.send_command_timing("\n")
        net_connect.disconnect
        print(output)
    
    

    我希望这会有所帮助。如果您还有其他问题,请告诉我

    【讨论】: