from napalm import get_network_driver
import json
import csv
import getpass
passwd = getpass.getpass('Please enter the password: ') # Reads the output from the user and save it as a string
driver = get_network_driver('ios')
cisco_01 = {
"hostname": 'cisco-router-01.packet.lan',
"username": "cisco",
"password": passwd,
"optional_args": {"secret": passwd}
}
switches = ['switch-01.packet.lan', 'switch-02.packet.lan']
switch_list = list()
for switch_ip in switches:
switch_dict = {
"hostname": switch_ip,
"username": "cisco",
"password": passwd,
"optional_args": {"secret": passwd}
}
switch_list.append(switch_dict)
device_router = driver(**cisco_01)
device_router.open()
print(f'Connecting to {cisco_01["hostname"]}')
napalm_output_router = device_router.get_arp_table()
print(json.dumps(napalm_output_router, indent=4))
device_router.close()
for each_switch in switch_list:
device_switch = driver(**each_switch)
device_switch.open()
print(f'Connecting to {each_switch["hostname"]}')
napalm_output_switch = device_switch.get_mac_address_table()
print(json.dumps(napalm_output_switch, indent=4))
for i in range(len(napalm_output_router)):
arp_mac = napalm_output_router[i]["mac"]
for n in range(len(napalm_output_switch)):
if arp_mac in napalm_output_switch[n]["mac"] and napalm_output_switch[n]["vlan"] == 20 and napalm_output_switch[n]["interface"] != 'Gi0/1':
print(f'{arp_mac} is connected to {each_switch["hostname"]} on {napalm_output_switch[n]["interface"]} and the IP is {napalm_output_router[i]["ip"]} ')
with open('mac_data.csv', 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
csvdata = (napalm_output_router[i]["ip"], arp_mac, each_switch["hostname"], napalm_output_switch[n]["interface"])
writer.writerow(csvdata)
device_switch.close()