您需要创建一个for loop
. Netmiko
接受ConnectHandler
类中的一本字典。因此,要使代码“为每个”设备运行,您必须创建一个循环。
此外,在for loop
您创建以从中读取 IP 地址的过程中,您每次都在循环中hosts.txt
不断覆盖dict。每次覆盖之前的值。应该将新值附加到列表中。cisco
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()
您可以通过 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'}]