agent: |
KXHnOn2qiFEdHtCRwY4AList All Users in Microsoft Entra ID(Azure AD)
List All 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 retrieves all user accounts within an Azure Active Directory tenant. It's essential for administrative tasks such as compliance, user management, and reporting, offering a comprehensive view of the user identities in an organization.
inputs
outputs
from azure.identity import DefaultAzureCredential, CredentialUnavailableError
from msgraph.core import GraphClient
import requests
# Define the scopes
scopes = ['https://graph.microsoft.com/.default']
try:
# 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)
# Send a GET request to list all users
users_response = client.get('/users')
users_response.raise_for_status() # Raise an exception for HTTP error responses
# Parse the response to JSON
users = users_response.json()
# Check if the response contains users
if not users.get('value', []):
print("No users found in Azure Active Directory.")
else:
# Header for the table
header = f"{'Display Name':<30} | {'User Principal Name':<55} | {'ID':<36}"
print(header)
print("-" * len(header))
for user in users['value']:
display_name = user.get('displayName', 'N/A')
user_principal_name = user.get('userPrincipalName', 'N/A')
user_id = user.get('id', 'N/A')
user_row = f"{display_name:<30} | {user_principal_name:<55} | {user_id:<36}"
print(user_row)
print("-" * len(header))
except CredentialUnavailableError as e:
print("Credential error occurred while authenticating to Azure AD:", e)
except requests.exceptions.HTTPError as e:
print("HTTP error occurred while making a request to the Graph API:", e)
except Exception as e:
print("An unexpected error occurred:", e)
copied