使用python脚本从交换机/路由器cisco保存启动配置吗?

问题描述 投票:0回答:1

我想自动备份我的交换机/路由器配置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个回答
0
投票

您将它们作为“配置命令”发送。在IOS中,必须从特权执行模式复制到TFTP服务器。如果从Global Config执行,则该命令将不起作用,除非它像do copy start tftp://...一样以“ do”开头。

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

您可以通过两种方式执行此操作:

  1. 就像您一样,通过TFTP备份到设备
  2. 通过捕获“ show run”命令的输出备份到文件
  3. 关于第二个选项的事情很酷:即使您的设备在连接TFTP服务器时遇到问题,您仍然可以备份配置。

方法1

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

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)

我希望这会有所帮助。让我知道是否还有其他问题

© www.soinside.com 2019 - 2024. All rights reserved.