简体   繁体   中英

how to read event logs under "Applications and Services Logs" in python?

I want to read some event logs that are under "Applications and Services Logs" preferably using pywin32 -> win32evtlog .

I can read event logs that are part of "System", "Application", "security" and other standard logs. but when I try to read some logs for example from "Microsoft-Windows-TWinUI/Operational", I will get logs of "Application".

according to MSDN the problem with getting "Application" logs instead of the desired logs is because the custom log cannot be found.

I tried to use something like the answer provided here but I can't seem to be able to do in python.

import win32evtlog

handle = win32evtlog.OpenEventLog(None, "Microsoft-Windows-TWinUI/Operational")
flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
if events:
   for event in events:
      print(event.StringInserts)

I prefer to use pywin32 but it is not a must and I can use other packages.

I know I'm a bit late, but in case anyone else is wondering this...

Use the newer Evt* functions in the library. You can access an xml of the event metadata from any log by using EvtQuery->EvtNext->EvtRender as outlined in the answer on this GitHub post: https://github.com/mhammond/pywin32/issues/676

PS The module win32evtlog's older functions (likeOpenEventLog) that return handles that are incompatible with the newer Evt* functions and vice versa. So avoid mixing them for sanity's sake! :)

There is clearly a lack of documentation and clear examples on the interwebs. Here is what I came up with after a fair amount of trial and error. The example below prints the latest event logs for Windows Defender alerts.

Hope someone that comes across this on their google journey finds this useful.

import win32evtlog
import xmltodict

def SearchEvents(LogName, EventId, count=20):
    EventLog = win32evtlog.EvtOpenLog(LogName, 1, None)

    #totalRecords = win32evtlog.EvtGetLogInfo(EventLog, win32evtlog.EvtLogNumberOfLogRecords)[0]
    ResultSet = win32evtlog.EvtQuery(LogName, win32evtlog.EvtQueryReverseDirection, "*[System[(EventID=%d)]]" % EventId, None)

    EventList = []
    for evt in win32evtlog.EvtNext(ResultSet, count):
        res = xmltodict.parse(win32evtlog.EvtRender(evt, 1))

        EventData = {}
        for e in res['Event']['EventData']['Data']:
            if '#text' in e:
                EventData[e['@Name']] = e['#text']

        EventList.append(EventData)

    return EventList


Events = SearchEvents('Microsoft-Windows-Windows Defender/Operational', 1116)
pprint(Events)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM