> For the complete documentation index, see [llms.txt](https://ph20eow.gitbook.io/tech-stuff/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ph20eow.gitbook.io/tech-stuff/silketw/learning-win32evtlog-in-python.md).

# 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.

## Getting Start

Basic example of reading "Security" event

```python
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

{% hint style="info" %}
The attribute of PyEventLogRecord listed in <http://timgolden.me.uk/pywin32-docs/PyEventLogRecord.html>
{% endhint %}

## Reading PyEventLogRecord

```python
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

```python
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"

```python
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

```python
try:        
    # Do something
except pywintypes.error as e:        
    print(e)    
```
