Read Specific Windows Event Log Event
Asked Answered
R

4

16

I am working on a program and need ot know how I would read a specific entry to the Windows Event Log based on a Record number, which this script will already have. Below is the code I have been working with, but I don't want to loop through all of the events until I find the one I'm looking for. Any ideas?

import win32evtlog

server = 'localhost' # name of the target computer to get event logs
logtype = 'System'
hand = win32evtlog.OpenEventLog(server,logtype)
flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
total = win32evtlog.GetNumberOfEventLogRecords(hand)

while True:
    events = win32evtlog.ReadEventLog(hand, flags,0)
    if events:
        for event in events:
            if event.EventID == "27035":
                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
                break
Rounders answered 27/6, 2012 at 3:59 Comment(1)
Remember to call win32evtlog.CloseEventLog(hand) when you're done.Salem
U
10

No! There are no functions available which allows you to obtain the event based on event id.

Reference: Event logging functions

GetNumberOfEventLogRecords  Retrieves the number of records in the specified event log.
GetOldestEventLogRecord     Retrieves the absolute record number of the oldest record 
                            in the specified event log.
NotifyChangeEventLog        Enables an application to receive notification when an event
                            is written to the specified event log.

ReadEventLog                Reads a whole number of entries from the specified event log.
RegisterEventSource         Retrieves a registered handle to the specified event log.

Only other method of interest is reading the oldest event.

You will have to iterate through the results any way and your approach is correct :)

You can only change the form of your approach like below but this is unnecessary.

events = win32evtlog.ReadEventLog(hand, flags,0)
events_list = [event for event in events if event.EventID == "27035"]
if event_list:
    print 'Event Category:', events_list[0].EventCategory

This is just the same way as you are doing but more succinct

Ujiji answered 27/6, 2012 at 5:16 Comment(3)
Great! I had found that information not too long ago! Thanks for the answer, I'll accept it when I can.Rounders
I don't know what the status was at the time that this answer was posted, but this is no longer correct (see my answer below - if you can write a WMI query, you can query it).Obedience
EventID is an integer. It will never match the string "27035"Jocundity
O
16

I realize this is an old question, but I came across it, and if I did, others may too.

You can also write custom queries, which allow you to query by any of the WMI parameters you can script (including event ID). It also has the benefit of letting you pull out and dust off all those VBS WMI queries that are out there. I actually use this functionality more frequently than any other. For examples, see:

Here's a sample to query for a specific event in the Application log. I haven't fleshed it out, but you can also build a WMI time string and query for events between or since specific date/times as well.

#! py -3

import wmi

def main():
    rval = 0  # Default: Check passes.
    
    # Initialize WMI objects and query.
    wmi_o = wmi.WMI('.')
    wql = ("SELECT * FROM Win32_NTLogEvent WHERE Logfile="
           "'Application' AND EventCode='3036'")
    
    # Query WMI object.
    wql_r = wmi_o.query(wql)

    if len(wql_r):
        rval = -1  # Check fails.
    
    return rval

    

if __name__ == '__main__':
    main()

Ten Years Later

While this answer is still valid, I suggest that anybody stumbling across it refer to this answer in the thread for a better solution.

Obedience answered 22/5, 2014 at 19:54 Comment(2)
Consider adding actual code to your answer and deferring to links only as references. You want to make the answer self-contained as you don't know when those links will expire.Fugitive
Thanks for the suggestion - I've gone ahead and done just that.Obedience
I
11

There is a python library now (python 3 and up) that will do what you're asking called winevt. What you're looking for could be done via the following:

from winevt import EventLog
query = EventLog.Query("System","Event/System[EventID=27035]")
event = next(query)
Impaction answered 6/5, 2017 at 19:2 Comment(0)
U
10

No! There are no functions available which allows you to obtain the event based on event id.

Reference: Event logging functions

GetNumberOfEventLogRecords  Retrieves the number of records in the specified event log.
GetOldestEventLogRecord     Retrieves the absolute record number of the oldest record 
                            in the specified event log.
NotifyChangeEventLog        Enables an application to receive notification when an event
                            is written to the specified event log.

ReadEventLog                Reads a whole number of entries from the specified event log.
RegisterEventSource         Retrieves a registered handle to the specified event log.

Only other method of interest is reading the oldest event.

You will have to iterate through the results any way and your approach is correct :)

You can only change the form of your approach like below but this is unnecessary.

events = win32evtlog.ReadEventLog(hand, flags,0)
events_list = [event for event in events if event.EventID == "27035"]
if event_list:
    print 'Event Category:', events_list[0].EventCategory

This is just the same way as you are doing but more succinct

Ujiji answered 27/6, 2012 at 5:16 Comment(3)
Great! I had found that information not too long ago! Thanks for the answer, I'll accept it when I can.Rounders
I don't know what the status was at the time that this answer was posted, but this is no longer correct (see my answer below - if you can write a WMI query, you can query it).Obedience
EventID is an integer. It will never match the string "27035"Jocundity
A
1

I see that the answers already cover the issues. Yet I want to add that if you need to retrieve specific logs of the events' time creation, you can do as follow:

import win32evtlog
from lxml import objectify
from datetime import datetime, timezone


def get_events(task_name, events_num):

    """
    task_name: a string from windows logs. e.g: "Microsoft-Windows-LanguagePackSetup/Operational"
    events_num: an integer for numbers of time creation. example: 10
    Output sample: 2022-03-09 08:45:29
    """
    handle = win32evtlog.EvtQuery(task_name, win32evtlog.EvtQueryReverseDirection , "*")
    event = win32evtlog.EvtNext(handle, 70, -1, 0)
    for i in event[-events_num:]:
        root = objectify.fromstring(win32evtlog.EvtRender(i, 1)) 
        paras =  root.System.TimeCreated
        d = datetime.fromisoformat(paras.attrib['SystemTime'][:23]).astimezone(timezone.utc)
        print(d.strftime('%Y-%m-%d %H:%M:%S'))

task_name = input("Enter the task name (e.g. Microsoft-Windows-ReadyBoost/Operational)")
events_num = int(input("Enter the number of logs"))
result = get_events(task_name, events_num)


if __name__ == "__main__": 
    print(result)

This is a great way to get specific logs. You can aim for more info than just the time creation from the XML file. This webpage provides neat explanations for Win32 Extensions http://timgolden.me.uk/pywin32-docs/contents.html

Aircondition answered 15/3, 2022 at 1:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.