Search code examples
pythonpywin32

Open Specific Event logs using win32evtlog Python


I want to open a specific log to the Windows Event Log, named "Microsoft-Windows-TerminalServices-LocalSessionManager". I used this code:

import win32evtlog

server = 'localhost' # name of the target computer to get event logs
logtype = 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\System\Microsoft-Windows-TerminalServices-LocalSessionManager'
hand = win32evtlog.OpenEventLog(server,logtype)
flags =  win32evtlog.EVENTLOG_SEQUENTIAL_READ|win32evtlog.EVENTLOG_FORWARDS_READ
total = win32evtlog.GetNumberOfEventLogRecords(hand)

while True:
    events = win32evtlog.ReadEventLog(hand, flags,0)
    if events:
        for event in events:
                print('Event Category:', event.EventCategory)
                print ('Time Generated:', event.TimeGenerated)
                print ('Source Name:', event.SourceName)
                print ('Event ID:', event.EventID)
                print ('Event Type:', event.EventType)
                data = event.StringInserts
                if data:
                    print('Event Data:')
                    for msg in data:
                        print(msg)

But it doesn't work, this code open "System" log, instead "Microsoft-Windows-TerminalServices-LocalSessionManager". Why it doesn't work? And if it is not a bug, but a feature, what is the way to read this log?

Thanks to your answer


Solution

  • You can only use first level subkeys like Application, HardwareEvents, Internet Explorer, System etc..

    sourceName specifies the name of the source that the returned handle will reference. The source name must be a subkey of a logfile entry under the EventLog key in the registry. win32evtlog.OpenEventLog

    If you specify a custom log and it cannot be found, the event logging service opens the Application log; however, there will be no associated message or category string file. OpenEventLogA function (winbase.h)

    However you can use win32evtlog.EvtQuery function for fetching events.

    Note: If you get Access Denied error, try to run with Run as Administrator

    import win32evtlog
    import xml.etree.ElementTree as ET
    
    # open event file
    query_handle = win32evtlog.EvtQuery(
        'C:\Windows\System32\winevt\Logs\Microsoft-Windows-TerminalServices-LocalSessionManager%4Operational.evtx',
        win32evtlog.EvtQueryFilePath)
    
    read_count = 0
    while True:
        # read 100 records
        events = win32evtlog.EvtNext(query_handle, 100)
        read_count += len(events)
        # if there is no record break the loop
        if len(events) == 0:
            break
        for event in events:
            xml_content = win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventXml)
            # print(xml_content)
    
            # parse xml content
            xml = ET.fromstring(xml_content)
            # xml namespace, root element has a xmlns definition, so we have to use the namespace
            ns = '{http://schemas.microsoft.com/win/2004/08/events/event}'
    
            event_id = xml.find(f'.//{ns}EventID').text
            level = xml.find(f'.//{ns}Level').text
            channel = xml.find(f'.//{ns}Channel').text
            execution = xml.find(f'.//{ns}Execution')
            process_id = execution.get('ProcessID')
            thread_id = execution.get('ThreadID')
            time_created = xml.find(f'.//{ns}TimeCreated').get('SystemTime')
            print(f'Time: {time_created}, Level: {level} Event Id: {event_id}, Channel: {channel}, Process Id: {process_id}, Thread Id: {thread_id}')
            
            user_data = xml.find(f'.//{ns}UserData')
            # user_data has possible any data
            
    print(f'Read {read_count} records')
    

    Output:

    Time: 2020-12-20T10:47:53.3790439Z, Level: 4 Event Id: 32, Channel: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational, Process Id: 1476, Thread Id: 1496
    Time: 2020-12-20T10:47:57.5636553Z, Level: 4 Event Id: 41, Channel: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational, Process Id: 1476, Thread Id: 1504
    Time: 2020-12-20T10:47:57.5662431Z, Level: 4 Event Id: 42, Channel: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational, Process Id: 1476, Thread Id: 1504
    Time: 2020-12-20T10:48:26.9395585Z, Level: 4 Event Id: 21, Channel: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational, Process Id: 1476, Thread Id: 1512
    Time: 2020-12-20T10:48:27.0466986Z, Level: 4 Event Id: 22, Channel: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational, Process Id: 1476, Thread Id: 10212
    Read 823 records