✨
Tech Stuff
  • Welcome
  • Threat Hunting
    • Learning ETW
      • Logman
      • SilkETW
      • Apply ETW to Windows Event (1)
    • Learning win32evtlog in python
  • Attack Simulation
    • Atomic Red Team
  • Tools
    • Windows Events Providers Explorer
    • FRIDA for iOS app penetration testing
  • Windows Security
    • User Account Control (UAC)
      • UAC Bypass
  • Windows OS Penetration Testing
    • Metasploit
    • PowerShell
    • Bloodhound
  • Unorganized Python
  • Python - pexpect
  • Python - subprocess for Windows
  • Parsing evtx to json
  • Python - Pykd
  • Workflow
    • Kali Linux on Docker
Powered by GitBook
On this page
  • Getting Start
  • Reading PyEventLogRecord
  • List All Available Log Types
  • Getting Event Logs in XML format
  • Error Handling

Was this helpful?

  1. Threat Hunting

Learning win32evtlog in python

WIn32evtlog is a module from pywin32 reading Windows Event Log. I found this library lack of examples, so I hope this page could help.

PreviousApply ETW to Windows Event (1)NextAtomic Red Team

Last updated 4 years ago

Was this helpful?

Getting Start

Basic example of reading "Security" event

import win32evtlog

computer = None # None = Local
logType = "Security"
h=win32evtlog.OpenEventLog(computer, logType)

flags= win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
evtLogs = win32evtlog.ReadEventLog(h, flags, 0)
evtLogs[0]

>>> <PyEventLogRecord at 0x221b8df0fd0>

Success! But it returned a PyEventLogRecord object

The attribute of PyEventLogRecord listed in

Reading PyEventLogRecord

evtLogs[0].SourceName
>>> 'Microsoft-Windows-Security-Auditing'

List All Available Log Types

The log type variable actuall only accept the list of channel names that are registered on the computer. To obtain the correct channel name, you could use EvtNextChannelEnum handler and EvtNextChannelPath. Of course @0xeb 's WEPExplorer can helps too

h = win32evtlog.EvtOpenChannelEnum(None)

while win32evtlog.EvtNextChannelPath(h) is not None:
    
    print(win32evtlog.EvtNextChannelPath(h))

Getting Event Logs in XML format

To achieve this, using EvtRender() and the EvtRenderEventXml flag. See example of query 4624 events from "Security"

channelName = "Security"

flags = win32evtlog.EvtQueryReverseDirection

evtQueryResultNo = 100

evtQuery = "*[System[(EventID=4624)]]"

evtQueryTimeout = -1



evtQueryResult = win32evtlog.EvtQuery(channelName, flags, evtQuery, None)

events = win32evtlog.EvtNext(evtQueryResult, evtQueryResultNo, evtQueryTimeout, 0)


for event in events:
    
    print(win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventXml))

Error Handling

As win32evtlog is just a module of pywin32, it offers a exception handling using pywintypes.error

try:
        
    # Do something
except pywintypes.error as e:
        
    print(e)
    
http://timgolden.me.uk/pywin32-docs/PyEventLogRecord.html