Getting number of active network connections to csv with Python

AnthonyCho
Here to help

Getting number of active network connections to csv with Python

Hello Forum

 

I have written the following code in Python to get the number of active connections per network.  However when I run it nothing happens

 

Python 3.12.6 (tags/v3.12.6:a4a2d2b, Sep 6 2024, 20:11:23) [MSC v.1940 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
import csv
import meraki
import requests

# Define your Meraki API key and organization ID
API_KEY = 'TOPSECRET'
ORG_ID = '00000'

# Base URL for Meraki Dashboard API
BASE_URL = 'https://api.meraki.com/api/v1'

# Headers for API calls
HEADERS = {
'X-Cisco-Meraki-API-Key': API_KEY,
'Content-Type': 'application/json'
}

def get_networks(org_id):
"""
Fetch the list of networks in the organization.
"""
url = f'{BASE_URL}/organizations/{org_id}/networks'
response = requests.get(url, headers=HEADERS)
response.raise_for_status()
return response.json()

def get_active_connections_count(network_id):
"""
Fetch active client count for a specific network.
"""
url = f'{BASE_URL}/networks/{network_id}/clients'
params = {
'timespan': 86400, # Last 24 hours
}
response = requests.get(url, headers=HEADERS, params=params)
response.raise_for_status()
clients = response.json()
return len(clients) # Each client in the list represents an active connection

def export_to_csv(data, filename='active_connections_per_network.csv'):
"""
Export data to a CSV file.
"""
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Network ID', 'Network Name', 'Active Connection Count'])
for row in data:
writer.writerow([row['network_id'], row['network_name'], row['active_connections']])

def main():
try:
# Step 1: Get all networks in the organization
networks = get_networks(ORG_ID)
# Step 2: Gather the counts
connection_data = []
for network in networks:
network_id = network['id']
network_name = network['name']
active_connections = get_active_connections_count(network_id)
connection_data.append({
'network_id': network_id,
'network_name': network_name,
'active_connections': active_connections
})
# Step 3: Export the results to a CSV file
export_to_csv(connection_data)
print("Exported active connection counts to active_connections_per_network.csv")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
if __name__ == '__main__':
main()

 

4 Replies 4
AnthonyCho
Here to help

Note that this code compiles successfully....

RaphaelL
Kind of a big deal
Kind of a big deal

I don't have the answer right away , but why are you not using the Meraki python SDK ?

AnthonyCho
Here to help

Because we're building BI Reports....

rhbirkelund
Kind of a big deal
Kind of a big deal

The formatting in your script is messed up a bit. Could you perhaps use the code block, and add your script there?

LinkedIn ::: https://blog.rhbirkelund.dk/

Like what you see? - Give a Kudo ## Did it answer your question? - Mark it as a Solution 🙂

All code examples are provided as is. Responsibility for Code execution lies solely your own.
Get notified when there are additional replies to this discussion.