设备列表中的 netmiko 连接仅连接到列表中的第一个 ip

问题描述

我正在使用 (基础) C:\python Python 3.8.8(认,2021 年 4 月 13 日,15:08:03)[MSC v.1916 64 位 (AMD64)] :: Anaconda,Inc. on win32 输入“help”、“copyright”、“credits”或“license”以获取更多信息。sing

创建于 2021 年 6 月 16 日星期三 10:15:59

import logging
from netmiko import ConnectHandler

logging.basicConfig(filename='test2.log',level=logging.DEBUG)
    logger = logging.getLogger("netmiko")
    with open('host.txt',"r") as host:
    for ip in  host.read().splitlines():
        cisco = {
        'device_type': 'cisco_ios','ip': ip,'username': 'user','password': 'password',}
    net_connect = ConnectHandler(**cisco)
    print (' #### Connecting to ' + ip)
    output = net_connect.find_prompt()
    print(output)

    net_connect.disconnect()

解决方法

您需要创建一个 for loopNetmiko 接受 ConnectHandler 类中的一本字典。因此,要使代码“针对每个”设备运行,您必须创建一个循环。

此外,在您创建的用于从 for loop 读取 IP 地址的 hosts.txt 中,您每次在循环中都会不断覆盖 cisco dict。 cisco = {} 每次都会覆盖先前的值。新值应该附加到列表中。

您可以通过以下方式实现:

from netmiko import ConnectHandler
import logging

logging.basicConfig(filename="test2.log",level=logging.DEBUG)
logger = logging.getLogger("netmiko")


with open(file="hosts.txt",mode="r") as hosts:
    # A list comprehension
    devices = [
        {
            "device_type": "cisco_ios","ip": ip,"username": "cisco","password": "cisco",}
        for ip in hosts.read().splitlines()
    ]

print(devices)  #  <--- print value is below

# Connect to each device (one at a time)
for device in devices:
    print(f'Connecting to {device["ip"]}')  # Here you are still trying to connect
    net_connect = ConnectHandler(**device)
    print(f'Connected to {device["ip"]}')  # Here you are already connected
    prompt = net_connect.find_prompt()
    net_connect.disconnect()  # disconnect from the session

    # Finally,print the prompt within the foor loop,but
    # after you disconnect. You no longer need the connection to print.
    print(prompt)

您可以使用 net_connect.disconnect() 语句忘记 with (Context Manager)

完成后清除 vty 线很重要

for device in devices:
    print(f'Connecting to {device["ip"]}')  # Here you are still waiting to connect
    with ConnectHandler(**device) as net_connect:
        print(f'Connected to {device["ip"]}')  # Here you are already logged-in
        prompt = net_connect.find_prompt()
    print(prompt)

如果您打印 devices 列表,您将获得:

[{'device_type': 'cisco_ios','ip': '192.168.1.1',# From hosts.txt file
  'password': 'cisco','username': 'cisco'},{'device_type': 'cisco_ios','ip': '192.168.1.2','username': 'cisco'}]