''' USAGE: 1) Create client in Keycloak and enable client authentication + service account roles for it 2) Assign "view-realm" role from realm-management client on "service account roles" tab for the client 3) Replace keycloak_url and realm_name variables with your Keycloak base dir 4) Export client credentials into $CLIENTID and CLIENTSECRET env variable 5) python get-keycloak-active-sessions.py ''' import requests import json import os keycloak_url = "https://keycloak" realm = "realm" client_id = os.getenv('CLIENTID') client_secret = os.getenv('CLIENTSECRET') grant_type = "client_credentials" auth_url = f"{keycloak_url}/auth/realms/{realm}/protocol/openid-connect/token" headers = {"Content-Type": "application/x-www-form-urlencoded"} data = {"grant_type": grant_type, "client_id": client_id, "client_secret": client_secret} response = requests.post(auth_url, headers=headers, data=data) token = response.json()["access_token"] api_url = f"{keycloak_url}/auth/admin/realms/{realm}/client-session-stats" headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} response = requests.get(api_url, headers=headers) data=response.content.decode("utf-8") json_data = json.loads(data) for item in json_data: print(item["clientId"], item["active"])