Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
I have code that grabs events from the event viewer but it gets the oldest instead of the most recent. Any ideas? The code is currently set so access "Forwarded Events" you can change that by replacing it with "Security" "System" etc.

What I have tried:

Python
import win32evtlog
import xml.etree.ElementTree as ET
import ctypes
import sys


def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return FalseC:\Windows\System32\winevt\Logs\

if is_admin():


    # open event file
    query_handle = win32evtlog.EvtQuery(
        'ForwardedEvents.evtx',
        win32evtlog.EvtQueryFilePath)

    read_count = 0
    a = 1
    while a == 1:
        a += 1
        # read 1 record(s)
        events = win32evtlog.EvtNext(query_handle, 1)
        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)
            # 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}'

            substatus = xml[1][9].text

            event_id = xml.find(f'.//{ns}EventID').text
            computer = xml.find(f'.//{ns}Computer').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')

            event_data = f'Time: {time_created}, Computer: {computer}, Substatus: {substatus}, Event Id: {event_id}, Channel: {channel}, Process Id: {process_id}, Thread Id: {thread_id}'
            print(event_data)

            user_data = xml.find(f'.//{ns}UserData')
            # user_data has possible any data

else:
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)

input()
Posted
Updated 5-Jan-21 9:21am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900