【问题标题】:how to take multiple outputs from a loop to outside in python(netmiko)如何在python(netmiko)中从循环中获取多个输出到外部
【发布时间】:2020-08-14 10:44:19
【问题描述】:

我是 python 的新手。我有代码可以使用 netmiko 在多个交换机上运行多个“显示命令”,当一切都在循环中时,它工作正常。但是,当我想通过将多个“显示命令”的输出分配为变量并将其打印在循环外时,只打印其中一个输出。

S1 = {
    'device_type': 'cisco_ios',
    'ip': '192.168.0.56',
    'username': 'admin',
    'password': 'admin'
    }

S2= {
    'device_type': 'cisco_ios',
    'ip': '192.168.0.57',
    'username': 'admin',
    'password': 'admin'
    }

all_devices = [S1,S2]


for devices in all_devices:
    print("\nLogging into the switch...")
    net_connect = ConnectHandler(**devices)
    net_connect.enable()
    cmd = ["show vlan brief", "\n","\n","show ip interface brief"]
    for show in cmd:
        output=net_connect.send_command(show)
        y = output

print(y)

【问题讨论】:

  • 嗯......你一直覆盖 y。使用列表并附加到它。只有y 的最后一个内容存在。在for devices in all_devices: 之前放置一个y = [] 并将y = output 替换为y.append(output)
  • 感谢@PatrickArtner 非常感谢!

标签: python python-3.x netmiko


【解决方案1】:

试试这个:

S1 = {
    'device_type': 'cisco_ios',
    'ip': '192.168.0.56',
    'username': 'admin',
    'password': 'admin'
    }

S2= {
    'device_type': 'cisco_ios',
    'ip': '192.168.0.57',
    'username': 'admin',
    'password': 'admin'
    }

all_devices = [S1,S2]

y = []

for devices in all_devices:
    print("\nLogging into the switch...")
    net_connect = ConnectHandler(**devices)
    net_connect.enable()
    cmd = ["show vlan brief", "\n","\n","show ip interface brief"]
    for show in cmd:
        output=net_connect.send_command(show)
        y.append(output)

for x in y:
    print(x)

【讨论】:

  • 如果您现在将y.appned 修复为y.append,您成功实现了我在对此问题的评论中所写的内容。恭喜。
最近更新 更多