Adding descriptions to switch port is beneficial, I have always done it and it always helps when trying to troubleshoot, as long as those descriptions are up to date of course.
I am new to programming and python and I think it is safe to say after seeing it in action and creating few of my own newbie scripts I am addicted.
I had to work on adding bunch of port descriptions on Juniper EX3400 switch ports. Doing it one at a time is no fun when you have to do multiple ports at a time. I decided to do this via python. After some trial and error I was able to come up with a script that uses an input of the Device ID and a CSV file to push out the changes.
I created a simple CSV file, that looked like this:
I am using dynamic ports on my lab switch so I started with this:
Next I ran my code, provided the device ID of my switch and got successful results. Screen shots below show the change based on what was in the CSV file.
#NOTE: THERE IS NO CONFIG MERGING. IT WILL OVER WRITE AND/OR CLEAR EXISTING PORT CONFIGURATION(S)
import json
import csv
import requests
from IPython.core.display import display
#This will ask the user to Enter Device ID.
device_id = input('Enter Device ID:')
validation = 'You Entered:'
display(validation + device_id)
#~~Site ID + Base URL~~
base_url = 'https://api.mist.com/api/v1/sites/:site-id/devices/'
#Add device ID to base URL
url = base_url + device_id
print(url)
#This csv file will contain all the port numbers and their descriptions
with open('sw_vars.csv', 'r') as csv_file:
reader = csv.reader(csv_file)
# next(reader)
devices = list(reader)
# print(devices)
for port,description in devices:
# print(port,description)
payload= {
"port_config": {},
}
for idx, (port,description) in enumerate(devices):
if idx == 0:
continue # This line skips the header
payload["port_config"][port] = {"description": description}
#print(json.dumps(payload))
data = (json.dumps(payload))
print(data)
headers = {
'Content-Type': 'application/json',
'Authorization': 'Token Your-Token-Goes-Here'
}
response = requests.request("PUT", url, headers=headers, data=data)
print('\n''Script Finished')
#NOTE: THERE IS NO CONFIG MERGING. IT WILL OVER WRITE AND/OR CLEAR EXISTING PORT CONFIGURATION(S). I have the script and sample csv file located at my GitHub Repo – artofrf.