Skip to content

Instantly share code, notes, and snippets.

@varunchandak
Created April 16, 2024 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varunchandak/78a531a190f2757716fc0e3652704af6 to your computer and use it in GitHub Desktop.
Save varunchandak/78a531a190f2757716fc0e3652704af6 to your computer and use it in GitHub Desktop.
Fetch Inactive users in Azure Entra ID Tenant for last N days

Azure Inactive User Audit Tool

This tool helps identify inactive users in an Azure AD environment by utilizing Azure CLI to fetch sign-in logs and a Python script to analyze these logs.

Functionality

  • Azure CLI Command: Fetches sign-in activity logs.
    az monitor activity-log list --offset 180d --query "[?contains(operationName.value, 'SignIn')]"
  • Python Script: Analyzes sign-in logs to determine which users have not been active within a specified number of days.

Usage

  1. Fetch Logs: Use the Azure CLI command provided to download the latest sign-in logs.
  2. Run Script: Execute the Python script to identify inactive users.
    python3 inactive_users.py 90
    Replace 90 with the number of days to check for user inactivity.

Requirements

  • Azure CLI installed and configured
  • Python 3.x
import json
import sys
from datetime import datetime, timedelta
if len(sys.argv) < 2:
print("Usage: python3 script.py <number_of_days>")
sys.exit(1)
number_of_days = int(sys.argv[1])
print("Number of days:", number_of_days)
# Load sign-in data
with open('signins.json', 'r') as file:
sign_in_data = json.load(file)['value']
threshold_date = datetime.now() - timedelta(days=number_of_days)
print("Threshold date for activity:", threshold_date)
active_users = set()
for entry in sign_in_data:
entry_date = datetime.strptime(entry['createdDateTime'], '%Y-%m-%dT%H:%M:%SZ')
if entry_date >= threshold_date:
active_users.add(entry['userPrincipalName'])
# Load all users data
with open('all_users.json', 'r') as file:
all_users_data = json.load(file)['value']
all_users = set(user['userPrincipalName'] for user in all_users_data)
inactive_users = all_users - active_users
print(f"Inactive users (not signed in within the last {number_of_days} days):")
if inactive_users:
for user in inactive_users:
print(user)
else:
print("No inactive users found.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment