使用python脚本从交换机/路由器保存startupconfiguration?

2024-04-18 03:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我尝试创建以下脚本:

#!/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()

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


Tags: test脚本configoutputnetbinenableconnect
1条回答
网友
1楼 · 发布于 2024-04-18 03:35:19

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

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

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

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

第二个选项很酷:即使您的设备在到达TFTP服务器时遇到问题,您仍然可以备份配置

方法1

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

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#

所以你必须准备好回答这两个问题

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

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)

我希望这是有帮助的。如果你还有任何问题,请告诉我

相关问题 更多 >