如何在 python 中使用 netmiko 在多个 cisco 设备上执行 ssh

问题描述

我正在尝试为多个设备运行下面的脚本,并且它仅适用于根据以下脚本的最后一个设备。

请您验证以下脚本,因为我需要使用 for 循环语句执行两个设备输出

from netmiko import ConnectHandler 
from getpass import getpass

password= getpass()

RTR_01 = {

         'device_type': 'cisco_ios','host': '10.10.10.10','username': 'admin','password': password,}

RTR_02 = { 'device_type': 'cisco_ios','host': '10.10.10.11',}

device_list = [RTR_01,RTR_02] 

for device in device_list: print('Connecting to the device :' + device ['host']) 

net_connect = ConnectHandler(**device)

output = net_connect.send_command('show ip interface brief')
print(output)
output = net_connect.send_command('show version')
print(output)

解决方法

您需要在 for 循环中缩进这些行

from getpass import getpass

from netmiko import ConnectHandler

password = getpass()

RTR_01 = {
    "device_type": "cisco_ios","host": "10.10.10.10","username": "admin","password": password,}

RTR_02 = {
    "device_type": "cisco_ios","host": "10.10.10.11",}

device_list = [RTR_01,RTR_02]

for device in device_list:
    print("Connecting to the device :" + device["host"])

    net_connect = ConnectHandler(**device)

    output = net_connect.send_command("show ip interface brief")
    print(output)
    output = net_connect.send_command("show version")
    print(output)

    net_connect.disconnect() # to clear the vty line when done

您的代码应如下所示:

from getpass import getpass

from netmiko import ConnectHandler

password = getpass()

ipaddrs = ["10.10.10.10","10.10.10.11"]

# A list comprehension
devices = [
    {
        "device_type": "cisco_ios","host": ip,}
    for ip in ipaddrs
]

for device in devices:
    print(f'Connecting to the device: {device["host"]}')

    with ConnectHandler(**device) as net_connect:  # Using Context Manager
        intf_brief = net_connect.send_command(
            "show ip interface brief"
        )  # Inside the connection
        facts = net_connect.send_command("show version")  # Inside the connection

        # Notice here I didn't call the `net_connect.disconnect()`
        # because the `with` statement automatically disconnects the session.

    # On this indentation level (4 spaces),the connection is terminated
    print(intf_brief)
    print(facts)

这是一个更好的代码版本,可以做同样的事情:

intf_brief

输出(factsActiveWindow)在连接外打印,因为不再需要会话来打印任何收集的值。