Last active
June 14, 2024 13:39
-
-
Save JayDoubleu/adcd02ae42a611dab42bd5077c792bf5 to your computer and use it in GitHub Desktop.
This script fetches user license assignments from Azure AD, checks for Power BI Pro licenses, and generates a report with user details and account status
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import requests | |
import subprocess | |
import logging | |
import argparse | |
import csv | |
from datetime import datetime | |
import uuid | |
def configure_logging(debug): | |
"""Configure logging based on the debug flag.""" | |
level = logging.DEBUG if debug else logging.INFO | |
logging.basicConfig(level=level, format='%(asctime)s - %(levelname)s - %(message)s') | |
def get_access_token(resource): | |
"""Get the access token for the specified resource.""" | |
result = subprocess.run(['az', 'account', 'get-access-token', '--resource', resource], | |
stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) | |
return json.loads(result.stdout.decode())['accessToken'] | |
def has_powerbi_pro_license(user_id, token): | |
"""Check if a user has a Power BI Pro license.""" | |
url = f"https://graph.microsoft.com/beta/users/{user_id}/licenseDetails" | |
headers = {"Authorization": f"Bearer {token}"} | |
response = requests.get(url, headers=headers) | |
response.raise_for_status() | |
licenses = response.json()['value'] | |
return any('POWER_BI_PRO' in license['skuPartNumber'] for license in licenses) | |
def get_user_details(user_id, token): | |
"""Get user details from Microsoft Graph API.""" | |
url = f"https://graph.microsoft.com/beta/users/{user_id}?$select=displayName,userPrincipalName,accountEnabled" | |
headers = {"Authorization": f"Bearer {token}"} | |
response = requests.get(url, headers=headers) | |
response.raise_for_status() | |
return response.json() | |
def fetch_user_assignments(account_sku_id, bearer_token): | |
"""Fetch user license assignments from the API.""" | |
base_url = 'https://main.iam.ad.ext.azure.com/api/AccountSkus/UserAssignments' | |
next_link = '' | |
headers = { | |
'x-ms-command-name': 'Licenses - GetUserLicenseAssignments', | |
'Authorization': f'Bearer {bearer_token}', | |
'Content-Type': 'application/json', | |
'x-ms-client-request-id': uuid.uuid4().hex | |
} | |
results = [] | |
while True: | |
params = { | |
'accountSkuID': account_sku_id, | |
'nextLink': next_link, | |
'searchText': '', | |
'columnName': '', | |
'sortOrder': 'undefined' | |
} | |
response = requests.get(base_url, headers=headers, params=params) | |
response.raise_for_status() | |
data = response.json() | |
results.extend(data.get('items', [])) | |
next_link = data.get('nextLink') | |
if not next_link: | |
break | |
return results | |
def generate_powerbi_pro_users_report(users, output_file): | |
"""Generate a report of Power BI Pro users with their account status.""" | |
token = get_access_token("https://graph.microsoft.com") | |
with open(output_file, 'w', newline='') as csvfile: | |
fieldnames = ['userId', 'userPrincipalName', 'status'] | |
writer = csv.DictWriter(csvfile, fieldnames=fieldnames) | |
writer.writeheader() | |
for user in users: | |
user_id = user['objectId'] | |
logging.info(f"Processing user: {user_id}") | |
if has_powerbi_pro_license(user_id, token): | |
user_details = get_user_details(user_id, token) | |
user_principal_name = user_details['userPrincipalName'] | |
status = 'enabled' if user_details['accountEnabled'] else 'disabled' | |
logging.info(f"User {user_id} ({user_principal_name}): Account is {status}.") | |
writer.writerow({'userId': user_id, 'userPrincipalName': user_principal_name, 'status': status}) | |
else: | |
logging.info(f"Skipping user {user_id} as they do not have a Power BI Pro license.") | |
def main(): | |
parser = argparse.ArgumentParser(description="Fetch user license assignments and generate a report of Power BI Pro users with their account status.") | |
parser.add_argument('--debug', action='store_true', help='Enable debug logging') | |
parser.add_argument('--verbose', action='store_true', help="Enable verbose output") | |
args = parser.parse_args() | |
configure_logging(args.debug or args.verbose) | |
account_sku_id = '<EREPLACE_WITH_TENANT_NAME>:POWER_BI_PRO' | |
bearer_token = get_access_token("74658136-14ec-4630-ad9b-26e160ff0fc6") | |
logging.info("Fetching user license assignments...") | |
results = fetch_user_assignments(account_sku_id, bearer_token) | |
with open('results.json', 'w') as f: | |
json.dump(results, f, indent=4) | |
logging.info("Data fetched successfully and stored in results.json") | |
logging.info("Loading user data from results.json...") | |
with open('results.json') as f: | |
users = json.load(f) | |
current_datetime = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') | |
output_file = f"powerbi_pro_users_report_{current_datetime}.csv" | |
logging.info(f"Creating report file: {output_file}") | |
generate_powerbi_pro_users_report(users, output_file) | |
logging.info(f"Report generated: {output_file}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment