Assign a group policy to a client via API

PhilipDAth
Kind of a big deal
Kind of a big deal

Assign a group policy to a client via API

I needed a script that could assign a group policy to a client.  I created the below script (in case it is useful to anyone else) that will assign a group policy to a client in every network in an org that the client appears in.

 

The original script was called meraki-client-gp.py.

 

 

#!/usr/bin/env python3
#
# Installation instructions
# meraki-client-gp uses dotenv to safely store your credentials.  Create a file called .meraki.env
# in your home directory.  For Linux this is typically /home/username.  For Windows this
# is typically c:\users\<username>.
# Into .meraki.env put this line:
# MERAKI_DASHBOARD_API_KEY=<your API key>
# If you don't have an API key yet then follow the instructions on this page:
# https://documentation.meraki.com/zGeneral_Administration/Other_Topics/The_Cisco_Meraki_Dashboard_API
#
# You need pip3 installed.  For Linux you can do this with:
# sudo apt install python3-pip
#
# Then install the Python modules:
# pip3 install --upgrade meraki
# pip3 install --upgrade python-dotenv
#
# For Linux, mark the Python script as executable:
# chmod +x meraki-client-gp.py
#
# Windows command line usage:
# python .\meraki-client-gp.py -o <org name> -c <client MAC address> -gp <group policy name>
# Linux command line usage:
# ./meraki-client-gp.py -o <org name> -c <client MAC address> -gp <group policy name>
#
# Example usage:
# python .\meraki-client-gp.py -o "Org name" -c "11:22:33:44:55:66" -gp "Normal"
# python .\meraki-client-gp.py -o "Org name" -c "11:22:33:44:55:66" -gp "Blocked"
# python .\meraki-client-gp.py -o "Org name" -c "11:22:33:44:55:66" -gp "Test Group Policy"
#

import os,argparse,meraki
from dotenv import load_dotenv

# Load in environment
load_dotenv()
load_dotenv(dotenv_path=os.path.join(os.path.expanduser("~"),".meraki.env"))

# Make sure we have an API key defined
if not os.getenv("MERAKI_DASHBOARD_API_KEY"):
	print("MERAKI_DASHBOARD_API_KEY must be defined in .meraki.env in your home directory or in .env in the current directory")
	exit(-1)

# Update the clients group policy
def getGroupPolicyId(dashboard,networkId,networkName,groupPolicy):
	groupPolicyId=None

	# Loop through the user defined network group policies looking for the correct one
	policies=dashboard.networks.getNetworkGroupPolicies(networkId)
	for policy in policies:
		if policy['name'] == groupPolicy:
			groupPolicyId=policy['groupPolicyId']
			break;
	
	if groupPolicyId==None:
		print(f"Group policy {groupPolicy} not found in network {networkName}")
		exit(-1)

	return(groupPolicyId)

# Update the clients group policy
def updateClientGroupPolicy(orgName,clientMAC,groupPolicy):
	orgId=None
	netId=None
	groupPolicyId=None

	# Initialize the Meraki SDK
	dashboard = meraki.DashboardAPI(
		output_log=False,
		print_console=False
	)

	# Search for the org
	orgs = dashboard.organizations.getOrganizations()
	for org in orgs:
		if org['name'] == orgName:
			orgId=org['id']
			break;
	if orgId == None:
		print("Invalid organization name supplied: "+orgName)			
		exit(-1)
	
	# Search for the client
	try:
		response = dashboard.organizations.getOrganizationClientsSearch(orgId, clientMAC)
	except Exception as e:
		print(f"Could fine find a client with the MAC address {clientMAC}")
		exit(-1)


	# Loop through all the networks that the client was found in
	clientId=response['clientId']
	for record in response['records']:
		netId=record['network']['id']
		description=record['description']
		networkName=record['network']['name']

		# See if we are using a built in group policy or a user defined policy
		if groupPolicy in ('Whitelisted','Blocked','Normal'):
			dashboard.networks.updateNetworkClientPolicy(netId, clientId, groupPolicy)
		else:
			groupPolicyId=getGroupPolicyId(dashboard,netId,networkName,groupPolicy)
			dashboard.networks.updateNetworkClientPolicy(netId,clientId,"Group policy",groupPolicyId=groupPolicyId)

		print(f"Updated {description} in {networkName}")

def main():
	text="""
	meraki-client-gp.py assigns a group policy to a client.
	In your home directory you should have a .meraki.env file containing MERAKI_DASHBOARD_API_KEY=<your API key>
	"""

	parser = argparse.ArgumentParser(description = text)
	parser.add_argument("-o", "--orgName", required=True, help="Meraki org name")
	parser.add_argument("-c", "--clientMAC", required=True, help="MAC address of the client")
	parser.add_argument("-gp", "--groupPolicy", required=True, help="Group policy to apply")

	args=parser.parse_args()

	updateClientGroupPolicy(args.orgName,args.clientMAC,args.groupPolicy)

main()

 

1 REPLY 1
BlakeRichardson
Kind of a big deal
Kind of a big deal

Awesome thanks for sharing, I love it when people share their work to help other people rather than keeping it to themselves. 

Get notified when there are additional replies to this discussion.