Click here to Skip to main content
14,877,782 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:

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

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

if is_admin():

    # open event file
    query_handle = win32evtlog.EvtQuery(

    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:

        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 = '{}'

            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}'

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

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

Updated 5-Jan-21 9:21am

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