Dev: VlansInventory.py
Hi there, previously I shared a script that would get the vlans and show them on screen. Another useful requirement that I wanted to solve was to store that information on a CSV format as an inventory file.
from netmiko import ConnectHandler
import csv
# inventory with the ip of switches
devices = open('devices')
for ip in devices:
session = {
'ip': ip,
'username': 'silesio',
'password': 'cisco',
'device_type': 'cisco_ios'
}
login = ConnectHandler(**session)
# get the vlans
output_vlan = login.send_command('show vlan brief', use_textfsm=True)
# get the hostname
output_hostname = login.send_command('show run | in hostname')
hostname = output_hostname.split(' ')
hostname = hostname[1]
# add hostname to all dictionaries
counter = 0
size = len(output_vlan)
for i in output_vlan:
while counter < size:
output_vlan[counter]['hostname'] = hostname
counter += 1
# the columns name
columns = ['vlan_id', 'name', 'status', 'interfaces', 'hostname']
# save the output to a new file
with open('Vlans_Inventory.csv', 'a+', newline='') as output_file:
inventory_file = csv.DictWriter(output_file, fieldnames=columns)
inventory_file.writeheader()
inventory_file.writerows(output_vlan)
print(output_vlan)
PS: I Just wanted to share a personal tip that may help you if you’re planning to start using python as well. If your background is anything else except Devops (html, java, python, c, c#...), my suggestion is to try these scripts and see the results. Don’t just take a course on Python or watch videos learning about tuples, dictionaries, thanos, loops, variables… Especially if you’re NE. Just start playing with 2 or 10 devices and automate most of the repetitive tasks that you do daily.
I hope you enjoyed this post, leave your comments below and I'll see you on the next one.