Bulk changes to multiple network devices

SOLVED
RustyJames85
Here to help

Bulk changes to multiple network devices

I see there is a JSON script for updating the attributes for devices but it only allows for one at a time. Does anything exist for updating tags or any attribute with one api call?

 

It also seems as though to update one attribute , it requires all attributes to be included in the script. Can someone please advise?

1 ACCEPTED SOLUTION

Below should get you what you want for updating address, tags, etc.  This scrip assumes you don't know your org Id and the network Id associated with each serial number.  If you know that information, you can modify the script to suit your needs.  To get your serial numbers into a list, you could read through a file and populate it that way also.  

 

The firewall rules would follow the same concept.

 
 
import meraki

apiKey = '123YourAPI_Key'  # You could also use an environmental variable for this
dashboard = meraki.DashboardAPI(api_key=apiKey)
# You will have to get the serial numbers you want to modify into a list.
devicesToModifyList = ['XXXX-XXXX-XXXX''XXXX-XXXX-XXXX']
# The address you want to update on the devices
newAddress = '123 Any Street, Small Town USA'
# The tags you want to update on the devices.  They must be separated by a space.
newTags = ' tag1 tag2 '

# This list will be populated with dictionaries of the network ID and serial number of the devices.
serialAndNetworkIdList = list()

print('Finding Org ID...')
# You first have to find your Org ID.  Replace 'Your Org Name' with whatever your org name is in the dashboard.
#  If you know your org Id, you can skip this part and set the orgId variable to it.
try:
    myOrgs = dashboard.organizations.getOrganizations()
except meraki.APIError as e:
    printf'Meraki API error: {e}')
except Exception as e:
    print(f'some other error: {e}')
                
for orgs in myOrgs:
    if orgs['name'] == 'Your Org Name':
        orgId = orgs['id']
print('DONE!')

# Pulls back all the devices that are assigned to a network in your org.  This can take some time if you have many devices.
# If you have many devices, it's recommended you use pagination.
devices = dashboard.devices.getOrganizationDevices(orgId, total_pages = 'all')

# This loops through all of the devices in your dashboard.  If the serial number is in your devicesToModifyList,
# it adds the network Id and serial number to the devicesToModifyDict.  The devicesToModifyDict is then appended
# to the serialAndNetworkIdList.

for device in devices:
    devicesToModifyDict = dict()
    if device['serial'in devicesToModifyList:
        devicesToModifyDict['networkId'] = device['networkId']
        devicesToModifyDict['serial'] = device['serial']
        serialAndNetworkIdList.append(devicesToModifyDict)

# This loops through serialAndNetworkIdList to update the devices.  You can add and remove things to the kwargs dictionary as needed.  Check the API docs
# for what you can add.
for device in serialAndNetworkIdList:
    networkId = device['networkId']
    serial = device['serial']
    kwargs = {
        'address': newAddress,
        'moveMapMarker'True,
        'tags': newTags
    }
    try:
        updateDevices = dashboard.devices.updateNetworkDevice(networkId, serial, **kwargs)
        print(updateDevices)
    except meraki.APIError as e:
        printf'Meraki API error: {e}')
        continue
    except Exception as e:
        print(f'some other error: {e}')
        continue

View solution in original post

13 REPLIES 13
PhilipDAth
Kind of a big deal
Kind of a big deal

You might need to give a specific example.

 

Here is an example of one API call and it lets you update lots of things at once.

https://dashboard.meraki.com/api_docs/v0#update-the-attributes-of-a-device 

 

Does it really make that much difference making muliple API calls?

Yes i have already explored that API call. What i am looking to do is to update lets say at least 10-25 devices (switches or APs) at once in the same network with new tags and or new address. This particular API call appears to only let you do one serial number at a time and requires all the attributes be completed.

 

Does that give a clearer picture?

 

It makes a difference because from what i am understanding i would have to change out the serial # for each call when i would like to just do one push and it pushes the "new tag" and/or "new address" to all the devices.

Yes i have already explored that API call. What i am looking to do is to update lets say at least 10-25 devices (switches or APs) at once in the same network with new tags and or new address. This particular API call appears to only let you do one serial number at a time and requires all the attributes be completed.



Does that give a clearer picture?



It makes a difference because from what i am understanding i would have to change out the serial # for each call when i would like to just do one push and it pushes the "new tag" and/or "new address" to all the devices.

I'm pretty new to the API myself so this may not be a comprehensive answer.  I'm doing something similar, renaming APs and so far I have been able to change 15 at once using that API call and Collection Runner in Postman.

 

Here's what I did:

*Install Postman and the Meraki Dashboard API Collection (the collection is optional, you can just type this in)

*Create a new request in Postman (either make environment variables for your API key, the baseURL, and networkId or just fill them in).  Here is what mine looks like.


          {{baseUrl}}/networks/{{networkId}}/devices/{{serial}}?name={{name}}

 

*Create a .csv file with two columns.  One has header "serial" and the other has header "name"

*Click Runner in Postman to open that window.  Choose the request you created above and use Select File to choose the .csv file

*Click Run Start

*Check the Meraki dashboard to see that it worked.

 

My command only updates the name, so any variables you don't change stay the same.  You should be able to change the name variable to be your tag variable instead and add another one for the address.

Here's a link to the Postman variable documentation that may help with adding another variable.  https://learning.postman.com/docs/postman/variables-and-environments/variables/

 

Hope that helps.

thanks unfortunately i am getting 404 error codes dont understand why.

i just first with your serial number but that doesn't work and neither with the tag inserted as a variable as well.

https://{{shard}}.meraki.com/api/v0/newtorks/{{network_Id}}/devices/Q2KD-XXXX-XXXX?name=AP001
Edgar-VO
Building a reputation

Hi

 

Using Postman is one way of doing it, however If you use Python and the Meraki API call, you can browse through that network, obtain all serials of the devices and the change the objects you want.... Done that several times already with my networks here.

 

here is an example of the things we use here. (identing is gone with cut and paste)

 

 

def Add_Network_Device(def_network,def_serial,def_site_code):

  #
  # First check if device is already in network
  #

  device_there = 0
  my_network_devices = dashboard.devices.getNetworkDevices(def_network)

  for my_network_device in my_network_devices:

if def_serial == my_network_device['serial']:
print ("device ",my_network_device["model"],"with serial",def_serial,"already added")
device_there = 1

if device_there == 0:

print ('Adding ',def_serial,' to netowrk id : ',def_network)

try:
response = dashboard.devices.claimNetworkDevices(def_network,serial=def_serial )
print (response)

except:
print ("Failed to add device")
quit()

my_device = dashboard.devices.getNetworkDevice(def_network,def_serial)

model_type = str(my_device['model'])

if model_type[:2] == "MX":
def_site_code += "-FW1"
elif model_type[:2] == "MS":
def_site_code += "-SW01"
elif model_type[:2] == "MR":
def_site_code += "-AP01"

param = {}

param['name'] = def_site_code

try:
response = dashboard.devices.updateNetworkDevice(def_network,def_serial,**param)
print (respons)
except:
print ("Cannot update ")

print ("Name is : ",def_site_code)

 

Have you looked into Action Batches?

I have played with those as well, but i am trying to familiarize myself with the best approach either python or utilizing postman. Anymore advice would be much obliged.

To be honest, I don't sue Postman so I can't comment on that.  If you want to update any attribute of a device, you have to do them one by one as the API identifies devices by serial number.  You could do a simple Python loop to take care of this for you.  You don't have to update all attributes, you can only update the ones you want.  If you have, say, 100 devices in your dashboard and only want to update 10-25 devices, how do you identify those 10-25 devices?  By name, tag, serial number, etc.?

By serial #, that is really what i am looking for. If i want to update an address or tag for a certain set of devices within a network then i would like to use a loop to hit say 5 or more devices. 

 

Or another would be if i want to add multiple firewall rules then i would like to do this with loop within python for example by the network id in the meraki dashboard.

Below should get you what you want for updating address, tags, etc.  This scrip assumes you don't know your org Id and the network Id associated with each serial number.  If you know that information, you can modify the script to suit your needs.  To get your serial numbers into a list, you could read through a file and populate it that way also.  

 

The firewall rules would follow the same concept.

 
 
import meraki

apiKey = '123YourAPI_Key'  # You could also use an environmental variable for this
dashboard = meraki.DashboardAPI(api_key=apiKey)
# You will have to get the serial numbers you want to modify into a list.
devicesToModifyList = ['XXXX-XXXX-XXXX''XXXX-XXXX-XXXX']
# The address you want to update on the devices
newAddress = '123 Any Street, Small Town USA'
# The tags you want to update on the devices.  They must be separated by a space.
newTags = ' tag1 tag2 '

# This list will be populated with dictionaries of the network ID and serial number of the devices.
serialAndNetworkIdList = list()

print('Finding Org ID...')
# You first have to find your Org ID.  Replace 'Your Org Name' with whatever your org name is in the dashboard.
#  If you know your org Id, you can skip this part and set the orgId variable to it.
try:
    myOrgs = dashboard.organizations.getOrganizations()
except meraki.APIError as e:
    printf'Meraki API error: {e}')
except Exception as e:
    print(f'some other error: {e}')
                
for orgs in myOrgs:
    if orgs['name'] == 'Your Org Name':
        orgId = orgs['id']
print('DONE!')

# Pulls back all the devices that are assigned to a network in your org.  This can take some time if you have many devices.
# If you have many devices, it's recommended you use pagination.
devices = dashboard.devices.getOrganizationDevices(orgId, total_pages = 'all')

# This loops through all of the devices in your dashboard.  If the serial number is in your devicesToModifyList,
# it adds the network Id and serial number to the devicesToModifyDict.  The devicesToModifyDict is then appended
# to the serialAndNetworkIdList.

for device in devices:
    devicesToModifyDict = dict()
    if device['serial'in devicesToModifyList:
        devicesToModifyDict['networkId'] = device['networkId']
        devicesToModifyDict['serial'] = device['serial']
        serialAndNetworkIdList.append(devicesToModifyDict)

# This loops through serialAndNetworkIdList to update the devices.  You can add and remove things to the kwargs dictionary as needed.  Check the API docs
# for what you can add.
for device in serialAndNetworkIdList:
    networkId = device['networkId']
    serial = device['serial']
    kwargs = {
        'address': newAddress,
        'moveMapMarker'True,
        'tags': newTags
    }
    try:
        updateDevices = dashboard.devices.updateNetworkDevice(networkId, serial, **kwargs)
        print(updateDevices)
    except meraki.APIError as e:
        printf'Meraki API error: {e}')
        continue
    except Exception as e:
        print(f'some other error: {e}')
        continue
Edgar-VO
Building a reputation

Small Function to write all serials of your network to an xls file

 

import meraki
import xlrd
import xlwt
from xlwt import Workbook
import json

 

api_key = '<your key>
dashboard       = meraki.DashboardAPI(api_key)
my_org = dashboard.organizations.getOrganizations()
 
for org in my_org:
        org_id = org['id']
        print(org['name'])
 
my_networks = dashboard.networks.getOrganizationNetworks(org_id)

 

def Get_Network_serials():

    wb = Workbook()
    sheet = wb.add_sheet('NW-Serials')

    row_nr = 0
    col_nr = 0

    for my_network in my_networks:
        
        sheet.write(row_nr,0,my_network['id'])
        sheet.write(row_nr,1,my_network['name'])

        col_nr  = 2

        my_devices = dashboard.devices.getNetworkDevices(my_network['id'])

        for my_device in my_devices:
            sheet.write(row_nr,col_nr,my_device['serial'])
            col_nr += 1

        row_nr += 1    

    wb.save('Network serials.xls')
 
############
# Main
############
 
Get_Network_serials()

If your API key is tied to multiple orgs, this will only get the devices of the last org it pulls back in the list.  To get all serials in all orgs, you would need to put everything in the "for org in my_org: loop".

Get notified when there are additional replies to this discussion.