0

我使用(基础)C:\python Python 3.8.8(默认,2021 年 4 月 13 日,15:08:03)[MSC v.1916 64 位(AMD64)] :: Anaconda, Inc. on win32 输入“帮助”, “版权”、“学分”或“许可”以获取更多信息。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()
4

1 回答 1

0

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

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

您可以通过执行以下操作来实现:

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()您可以通过 usingwith语句忘记(上下文管理器)

完成后清除 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',  # From hosts.txt file
  'password': 'cisco',
  'username': 'cisco'}]
于 2021-08-02T20:08:56.607 回答