首页 > 解决方案 > Netmiko/Python 脚本不显示来自多个设备的输出

问题描述

当我运行脚本时,它只返回第一个设备的输出。

#!/usr/local/bin/python3.6
import netmiko
from netmiko import ConnectHandler
import getpass
from getpass import getpass
exceptions = (netmiko.ssh_exception.NetMikoTimeoutException, netmiko.ssh_exception.NetMikoAuthenticationException)

     router = {
    'device_type': 'cisco_ios',
    'ip': '10.5.5.1',
    'username': 'admin',
    'password': getpass(),
    'secret': getpass("Enable: "),
    'global_delay_factor': 2,
}

     switch = {
    'device_type': 'cisco_ios',
    'ip': '10.5.5.2',
    'username': 'admin',
    'password': getpass(),
    'secret': getpass("Enable: "),
    'global_delay_factor': 2,
}

list_of_devices = [router, switch]
for devices in list_of_devices:
    connector = ConnectHandler(**devices)


connector.enable()
print(connector)
output = connector.find_prompt()
output += connector.send_command('show ip arp', delay_factor=2)
print(output)

connector.disconnect()

标签: python-3.xfreebsdparamiko

解决方案


您需要在 for 循环中包含所有 Netmiko 操作。使用您当前的代码,您在第一台设备上建立连接,然后转到第二台设备并对其进行操作。您实际上并没有对第一个设备做任何事情(因为 for 循环内唯一的事情是 ConnectHandler 调用):

所以像这样(for循环部分):

list_of_devices = [router, switch]
for devices in list_of_devices:
    connector = ConnectHandler(**devices)
    connector.enable() 
    print(connector) 
    output = connector.find_prompt() 
    output += connector.send_command('show ip arp', delay_factor=2) 
    print(output)    
    connector.disconnect()

推荐阅读