Meraki – Gather Network Clients via API with Python – Pt. 1

Gather Network Clients via API

Overview

This guide will provide you with steps to obtain new a list of devices that have joined the Meraki network. This can be a useful dataset to have, outside of the Meraki dashboard for specific alerting cases, such as being alerted when a new device joins the network – as this is currently not an available feature.

How is this helpful?

As Cybersecurity insurance requirements grow, we have found that most Cybersecurity insurance companies require organizations to keep a list of the date/time & computer name of when a new device joins the network.

Prerequisites:

  • Must install python and all dependencies (see below for how to do this) on a local machine or cloud instance.
  • Must generate and obtain a Meraki API key (see below).
  • Familiarity with Python will be very helpful for troubleshooting Visual Studio Code or file path errors.
  • Install Microsoft Visual Studio Code (Not required- but helpful) at the following URL: Download Visual Studio Code – Mac, Linux, Windows

Install Python3

Install Python3 at the following URL: Download Python | Python.org
For the purpose of this document, I will be using Microsoft Visual Studio code to maintain and run the python script- but feel free to use the code editor you are most comfortable with.

Once Visual Studio code, and Python3 are installed, you will then need to open VS Code and install a python package. This can be done from a windows command prompt, or inside of vs code.


Optional (but recommended) Steps

Generally, it is a good idea to create an environment variable on your machine to store your API key in, vs pasting the API key directly in your python script. An environment variable is a way to store a value and call it by the name you give. Keeping your API key in plain text is a security risk, as it would grant full API access to your network to anyone that has it.

Also, generating Virtual Environment is another optional step. This keeps your python script in its own new file structure and is useful for keeping the script isolated, with its own package repository.


Python Package

The package to be installed are:

  • Meraki

Use the following commands to install the packages in the terminal, or in a windows command prompt after running python3:

pip install Meraki

You should see the files download and install automatically after running the command above, from either the windows command prompt, PowerShell, or though the terminal in visual studio code.


Obtain Meraki API Key

Next, we will need to obtain an API key. If you already have your Meraki API key, you can skip to the next section.

To obtain your Meraki API key, go to Organization settings → API and Webhooks → API Keys and access → Generate an API key. For more details on the Meraki API Key, see Meraki’s Documentation here: Cisco Meraki Dashboard API – Cisco Meraki Documentation

You must securely store the API key, as it will not be accessible via the Meraki API webpage in the future.


Obtain Organization, and network IDs.

A pre-requisite to using the Meraki API is obtaining your ORG and Network IDs. If you already know your ORG and Network IDs, you can skip to the next section.

To obtain your Meraki ORG ID, you can copy, and save the following python script as a .py filetype, then open it in Visual Studio Code

#Requires meraki package to be installed.
import meraki
import json

#If you are using an environment variable, use import os to call a locally stored variable
import os

#The example below uses an environment variable called org_ID that stores the value of the org ID.
org_id = os.environ["org_id"]

#The example below uses an environment variabled named MERAKI_DASHBOARD_API_KEY, that stores the value of my API key.
API_Key=os.environ["MERAKI_DASHBOARD_API_KEY"] 

#If you are not using an environment variable, paste it in plain text below.Delete the API= statement above.
#API_Key='PASTE-HERE'



#Using the Meraki package, this will gather the org ID(s) that your API key has permission to see.
dashboard = meraki.DashboardAPI(API_Key)
response = dashboard.organizations.getOrganizations()

#Prints the response to the API GET above, and outputs a JSON file with details.
print(response)
with open('ORGresponse.json', 'w') as f:
    json.dump(response, f, indent=4)

Once you have the script saved, and Meraki and JSON modules installed, you can run the script by pressing the play button in the upper right-hand corner of VS Code:

You may get an error message using the play button if visual studio code is not set to use the proper interpreter view. Press CTRL+SHIFT+P and search Python: Select Interpreter and ensure you have the right path to your virtual environment.

Once you run this script, the terminal should populate with the ORG ID, as well as there should be a new JSON file in the same directory that you saved the script. Save the ORG ID, for later use. The same process can be used to obtain the network ID, with the following Python script:

import meraki
import json
 
#Implement your own API key here.
API_Key='Paste-Your-API-Key-Here'

#Edit the org ID with the company you want to pull the networks for, from the previous step.
org_id = 'Paste-Your-Org-ID-Here'

#API GET network IDs.
dashboard = meraki.DashboardAPI(API_Key)
response = dashboard.organizations.getOrganizationNetworks(org_id)

#Print the response, and save to a JSON file.
print(response)
with open('NetworkIDresponse.json', 'w') as f:
    
    json.dump(response, f, indent=4)

Instead of using your API key directly in your code, it is more secure to map this as an Environment Variable.


Meraki Clients Connected Script

Now that you have the org ID, and Network ID (along with the NetoworkIDresponse.json file) for your Meraki network, we can plug those values into the following script that will do the following:

  • Gathers list of devices on the network, for every network ID in an organization- along with some data points on the client

Copy this script and save as a .py file in vs code and click run.

import meraki
import json
import os


API_Key=os.environ["MERAKI_DASHBOARD_API_KEY"] 

dashboard = meraki.DashboardAPI(API_Key)

#Update your ORG ID value below.
org_id = os.environ["org_id"] 

#Opens the NetworkIDresponse.json file. May need to influde the filepath if the file is not stored in the proper folder of the virtual environment.
with open('NetworkIDresponse.json', 'r') as f:
    networks = json.load(f)

#For each network seen in the NetworkIDResponse file, run a Get network clients request.
for network in networks:
    network_id = network['id']
    network_name = network['name']
    print(f'[API]*********Running API GET for {network_name}*********')
    response = dashboard.networks.getNetworkClients(
        network_id, perPage=1000, total_pages='All'
    )
    
    print(f'[API]*********{network_name} API Request Completed.The .JSON output files have been created.....*********')

    # Use json.dump to write the dictionary to a file named Networkname-response.json
    with open(f'{network_name}-response.json', 'w') as f:
        json.dump(response, f, indent=4)

Troubleshooting

KeyError

Error Message Example:

Traceback (most recent call last):
  File "Filepath\Api-Get-NetworkClients.py", line 6, in <module>
    API_Key=os.environ["MERAKI_DASHBOARD_API_KEY1"]
            ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen os>", line 685, in __getitem__
KeyError: 'MERAKI_DASHBOARD_API_KEY'
(merakiapi) PS C:\Folder> 
pip install meraki

This can be caused by a few potential problems:

  1. You have not created an environment variable on your system. Check out this article on how to set your Environment Variable to your API Key. I named mine MERAKI_DASHBOARD_API_KEY in the script above.
  2. The API Key is using an environment variable that you just created. If so, try saving your script, and re-starting Visual Studio Code. It will only be available after restarting the program after creating the API key in your systems environment variables.
  3. You do not have your Variable Value set as a valid API key.

FileNotFoundError

Traceback (most recent call last):
  File "C:\FilePath\FilePath\Scripts\Api-Get-NetworkClients.py", line 14, in <module>
    with open('NetworkIDresponse.json', 'r') as f:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'NetworkIDresponse.json'

File Not Found indicates you do not have a file named ‘NetworkIDresponse.json‘ in a directory your script can access. I would recommend creating a virtual environment, following this guide: Environments in Visual Studio Code. Ensure that you start over from scratch if creating a new environment. You will need to move the NetworkIDresponse.jsonfile to your newly created virtual environment folder, and re-install Meraki via pip install meraki (after CDing to your new virtual environment folder).

You may also see an error FileNotFoundError: [Errno 2] No such file or directory: 'New-Clients.csv', follow the same steps from above to troubleshoot.

Next Steps

Once you have the script above working, and a .JSON file being created per network, see the next article in this series to be alerted automatically when a new client connects to the network at his link: https://covene.com/gather-network-clients-pt-2/

Reference

The below website provides additional instructions for utilizing this process.

Introduction – Meraki Dashboard API v1 – Cisco Meraki Developer Hub


Contact Us

If you have questions, would like to leave feedback, or want to discuss another topic, please contact us using one of the methods below. We look forward to speaking with you!

Phone: 314-888-2511

Email: [email protected] or [email protected]

Website: https://covene.com/contact-us/


Discover more from Covene

Subscribe to get the latest posts sent to your email.

Leave a Reply