使用 Netmiko 循环遍历文件并获取交换机 ARP 条目

Use Netmiko to loop through file and get switch ARP entries

我正在尝试使用 Netmiko 输出交换机的 ARP table。我想使用一个包含 IP 地址的文件,然后让 Python/Netmiko 运行 一个“show arp”,然后从我提供的文件中添加 IP 地址。我希望它循环遍历 IP 地址文件以显示文件中 IP 地址的所有 ARP 条目,然后输出到包含 IP 和 MAC 地址的文件。以下是我的单个地址,如有任何帮助,我们将不胜感激:

#!/usr/bin/env python3
#CF extract ARP table and send output as text file

from netmiko import ConnectHandler
from datetime import datetime
import time
import sys

##initializing device
device = {
    'device_type': 'hp_comware',
    'ip': '10.1.10.10',
    'username': 'xxxx',
    'password': 'xxxx',
}
start_time = datetime.now()
print (start_time)

net_connect = ConnectHandler(**device)
output = net_connect.send_command("dis arp 172.16.100.100")
time.sleep(2)
filename="test-arp.txt"
saveconfig=open(filename, 'w+')
saveconfig.write(output)
saveconfig.close()
time.sleep(2)
net_connect.disconnect()
end_time = datetime.now()
print (end_time)

通过下面的代码,您可以根据设备的提示,非常快速地同时对100台设备进行操作(如果需要可以增加)。

from netmiko import Netmiko
from multiprocessing.dummy import Pool as ThreadPool
import time

f_2 = open("multiple_device_list_cisco.txt","r") # You should open a notepad with this name and add all the IPs one under the other.
multiple_device_list = f_2.readlines()

file1 = open("Result.txt", "a") # this will be your automatic output when the code is finished

def _ssh_(nodeip):

    try:
        hp = {
            'device_type': 'hp_comware', 'ip': nodeip, 'username':
            xxxx, 'password': xxxx, 'secret':xxxx, "conn_timeout": 20}
        hp_connect = Netmiko(**hp)
        print(nodeip.strip() + "  " + "is reachable")
    except Exception as e:
        print (e)
        f_3.write(nodeip.strip() + "\n")
        return

    prompt_hp_fnk = hp_connect.find_prompt()
    hostname_fnk = prompt_hp_fnk.strip("#") # Here you should put whatever the prompt of your HP device is
    print(hostname_fnk)
    output = hp_connect.send_command_timing("dis arp "+ nodeip)
    file1.write(nodeip +" "+ output+ "\n")
    hp_connect.disconnect()

myPool = ThreadPool(100) # you can increase or decrease this value
result = myPool.map(_ssh_,multiple_device_list)

我对上面的代码进行了必要的修改。希望有用