Search code examples
pythonnetworkingnetmiko

Use Netmiko to loop through file and get switch ARP entries


I am trying to output the ARP table of a switch by using Netmiko. I would like to use a file containing IP addresses and then have Python/Netmiko run a "show arp" and then add the IP address from the file I give. I would like it to loop through the IP address file to show all ARP entries for the IP addresses in the file and then output to a file containing both IP and MAC addresses. Below is what I have for a single address any help would be greatly appreciated:

#!/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)

Solution

  • With the code below, you can perform the operation very quickly on 100 devices at the same time (you can increase it if you want) in accordance with the promt of the device.

    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)
    

    I wrote the necessary changes to the above code. I hope that will be useful