Search code examples
pythonpowershellazure-active-directoryazure-automation

Alternate way to get Azure AD sign in logs in Python without using subprocess library and powershell.exe


As far as I can tell by looking at other posts, using the subprocess library in Python is the most popular way to execute PowerShell commands from within Python. For example:

data = subprocess.check_output(["powershell.exe", "Connect-AzureAD -AccountId me@me.com \n Get-AzureADAuditSignInLogs"]).decode(sys.stdout.encoding)

However, I'm ultimately trying to add this script to an automation account in Azure. Specifying the executable "powershell.exe" in the script won't work in an Azure automation account runbook (raises a "FileNotFound" error).

Is there some other way you can get the sign in log data from within Python that would be more amenable to using in an Azure automation account runbook? Can the Azure library be used to get sign in log data instead?


Solution

  • I have tested in my environment

    You can use MS Graph API query in your python script to get the Azure AD sign in logs of the users

    You can use below python code:

    import requests
    import json
    
    url = 'https://graph.microsoft.com/v1.0/auditLogs/signIns'
    token = "access_token"
    
    headers = {
     'Authorization': 'Bearer {}'.format(token)
    }
    
    user_response_data = json.loads(requests.get(url, headers=headers).text)
    print(user_response_data)
    

    Reference: Querying Microsoft Graph API with Python | by Ephraim Mwai | Towards Data Science