Sign in
agent:

Filter Out Inactive Users in Microsoft Entra ID (Azure AD)

There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.

This task identifies users in Azure Active Directory who haven't been active for a specified period. This aids in enhancing security and managing user accounts efficiently, enabling actions like account review or deactivation for better organizational control and security compliance.

from azure.identity import DefaultAzureCredential from msgraph.core import GraphClient from datetime import datetime, timedelta # Define the scopes scopes = ['https://graph.microsoft.com/.default'] # Initialize the DefaultAzureCredential to handle the authentication credential = DefaultAzureCredential() # Instantiate the GraphClient with the credential and the specified scopes client = GraphClient(credential=credential, scopes=scopes) # Define the threshold for inactivity (in days) inactive_days_threshold =30 # Calculate the cutoff date for inactivity (timezone-naive for comparison) cutoff_date = datetime.utcnow() - timedelta(days=inactive_days_threshold) users_data = users # Check if users data is available if not users_data.get('value'): print("No users found in Azure Active Directory.") else: inactive_users = [] for user in users_data['value']: display_name = user.get('displayName', 'N/A') upn = user.get('userPrincipalName', 'N/A') sign_in_activity = user.get('signInActivity', {}) last_sign_in = sign_in_activity.get('lastSignInDateTime') if last_sign_in: last_sign_in_date = datetime.fromisoformat(last_sign_in.replace('Z', '+00:00')).replace(tzinfo=None) if last_sign_in_date < cutoff_date: inactive_users.append(user) else: inactive_users.append(user) print(f"Found {len(inactive_users)} inactive users based on the {inactive_days_threshold}-day threshold.") for user in inactive_users: display_name = user.get('displayName', 'N/A') upn = user.get('userPrincipalName', 'N/A') last_sign_in = user.get('signInActivity', {}).get('lastSignInDateTime', 'No sign-in activity recorded') print(f"User: {display_name} ({upn})") print(f" Last Sign-In: {last_sign_in}") print("-" * 30) #print(users_data) # for debugging #print(inactive_users) # for debugging
copied