[python-win32] Reading events from event logs using wmi

Tim Golden mail at timgolden.me.uk
Wed Mar 19 15:08:33 CET 2008

Daren Russell wrote:
> Thanks for that.  I have found an example for what I want written in 
> VBS, which is why I tried the for... loop I mentioned, as that is 
> basically what that script did (though I'm even worse at vbs than I am 
> with Python ;-) )
> I've found details on the MSDN site, listing the class and now I (sort 
> of!!) understand how it links in with your wmi module, but is there a 
> way to get all events in one go, as that is basically what I need to do 
> to write a text version of the log to an archive.  If I leave the 
> EventType parameter out, it defaults to '3' - I guess I could do 
> multiple queries and then sort the output by retrieved dates, but it 
> seems a bit long winded!

The way WMI works in general is that you issue a pseudo-SQL
query against a pseudo-database and wait for a pseudo-rowset
to be returned. You can add a WHERE clause to narrow things down.

The wmi module wraps the fiddly plumbing needed to make
the connection in the first place and makes typical
queries pythonic so that a WQL query like:

SELECT Logfile, RecordNumber
FROM Win32_NTLogEvent
WHERE Logfile = "Application"


wmi.WMI ().Win32_NTLogEvent (Logfile="Application")

(Most queries are along the lines of: What are the
network devices active on my machine? What are the
phyiscal partitions on my disks? etc.)

Clearly this only works for equi-filters; if you need
to do things like "AND TimeGenerated > '20080101'" then
you'll need to call the .query method of the wmi namespace
which passes the WQL along to the WMI subsystem directly.
Even then, the objects returned are wrapped to be easier
to handle under Python.

To get any of the WMI stuff unqualified, you simply pass no qualifiers
at all. So... (be prepared for a long wait).

import csv
import wmi
c = wmi.WMI ()

writer = csv.writer (open ("logs.csv", "wb"))
writer.writerows (
   ) for log in c.Win32_NTLogEvent ())



More information about the python-win32 mailing list