Export switch configuration using Python script

H2O
New here

Export switch configuration using Python script

Hello,

 

Newbie looking some help with Python/Meraki API

 

Trying to get a switch configuration exported to an Excel sheet to then re-import into another network/Orgs, having issues with the line  "sp_data['PortId'].append(port['number'])" and with the line

"sp_data['Access Policy Number'].append(port['accessPolicyNumber'])". I get a KeyError: 'number'/ KeyError: 'accessPolicyNumber'..... not sure how to solve these

When I remove both of these lines and update the sp_data array the csv exports fine.
import os
import requests             # handles api requests in python
import pandas as pd         # handles dataframes in python
from getpass import getpass # prompts the user for input without echoing

MERAKI_API_KEY = 'X-Cisco-Meraki-API-Key'
MERAKI_API_VALUE = os.environ.get("MERAKI_API_KEY")

serial = input('Enter the serial number of the switch: ')

# Call switch port API
switch_req = requests.get('https://api.meraki.com/api/v1/devices/' + serial +'/switch/ports', 
                            headers = {MERAKI_API_KEY : MERAKI_API_VALUE})

# Check to ensure correct API response
if switch_req.status_code != 200:
    raise Exception(f'HTTP response was {switch_req.status_code}, and 200 was expected. ' +
                    'Please ensure your Meraki API Value and switch serial number are correct.')
else:
    # Read json response
    switch_ports = switch_req.json()

# Build dictionary to organize switch port info
sp_data = {'Switch' : [], 'PortId' : [], 'Name' : [], 'Tags' : [], 'Enabled' : [], 'PoE Enabled' : [],
           'Type' : [], 'VLAN' : [], 'Voice VLAN' : [], 'Allowed VLANs' : [], 'Isolation Enabled' : [],
           'RSTP Enabled': [], 'STP Guard': [], 'Access Policy Number' : [], 'Link Negotiation' : []}

# Iterate over the switch ports to fill dictionary
for port in switch_ports:
    sp_data['Switch'].append(serial)
    sp_data['Name'].append(port['name'])
    sp_data['PortId'].append(port['number'])
    sp_data['Tags'].append(port['tags'])
    sp_data['Enabled'].append(port['enabled'])
    sp_data['PoE Enabled'].append(port['poeEnabled'])
    sp_data['Type'].append(port['type'])
    sp_data['VLAN'].append(port['vlan'])
    sp_data['Voice VLAN'].append(port['voiceVlan'])
    sp_data['Allowed VLANs'].append(port['allowedVlans'])
    sp_data['Isolation Enabled'].append(port['isolationEnabled'])
    sp_data['RSTP Enabled'].append(port['rstpEnabled'])
    sp_data['STP Guard'].append(port['stpGuard'])
    sp_data['Access Policy Number'].append(port['accessPolicyNumber'])
    sp_data['Link Negotiation'].append(port['linkNegotiation'])

# Build switch port dataframe
switch_port_df = pd.DataFrame(data = sp_data)


# Write dataframe to csv
switch_port_df.to_csv(path_or_buf = serial + '_ports.csv', index = False)

print(f'The switch port information has been stored in {serial}_ports.csv')

 Thanks

4 Replies 4
Greenberet
Head in the Cloud

My guess: it is not available for each port configuration:

Greenberet_0-1696371430937.png

So if it the Type isn't "Custom access policy", then the field will not be here. That's why you are getting the error

Brash
Kind of a big deal
Kind of a big deal

@Greenberet is correct.
I'd also suggest exporting as a JSON file as it's easier to import back into the switch.
That said, it is less readable is readability is more important.

RaphaelL
Kind of a big deal
Kind of a big deal

3 main things. 

 

1- No Access Policy on trunk. So  "accessPolicyType":"Open" all the time.

2- Access ports can be either "accessPolicyType":"Open" or "accessPolicyType":"Custom access policy"

3- If Open , no Access policy number. Else Access policy number = port['accessPolicyNumber']

 

 

if port['accessPolicyType'] == "Custom access policy":

    sp_data['Access Policy Number'].append(port['accessPolicyNumber'])

else:

    sp_data['Access Policy Number'].append("NA")

 

also you are missing some other configs. DAI , Accesspolicytype  ( maybe more ) 

 

Hope I'm right on that one !

GreenMan
Meraki Employee
Meraki Employee

Applause for looking at the use case yourself, but I think a bunch of scripts already exist out there for this (try GitHub) - including this one of Phil's : https://www.ifm.net.nz/cookbooks/meraki-backup.html

Get notified when there are additional replies to this discussion.