python - 使用 pywin32(win32evtlog 模块)在 Python 中读取 Windows 事件日志

标签 python python-2.7 winapi event-log pywin32

我想阅读 Windows 的事件日志。我不确定这是否是最好的方法,但我想使用 pywin32 -> win32evtlog 模块 来这样做。首先也是最重要的是,是否可以使用此库从 Windows 7 读取日志,如果可以,如何读取与应用程序运行相关的事件(我猜运行 .exe 必须在 Windows 的事件日志中留下痕迹).

我设法在网上找到了一些小例子,但这对我来说还不够,不幸的是文档写得不好;/

import win32evtlog

hand = win32evtlog.OpenEventLog(None,"Microsoft-Windows-TaskScheduler/Operational")
print win32evtlog.GetNumberOfEventLogRecords(hand)

最佳答案

您可以在 C:\PythonXX\Lib\site-packages\win32\Demos 文件夹中找到大量与 winapi 相关的演示。在此文件夹中,您会找到一个名为 eventLogDemo.py 的脚本。在那里您可以看到如何使用 win32evtlog 模块。只需使用 eventLogDemo.py -v 启动此脚本,您就会从 Windows 事件日志中获取日志类型为 Application 的打印件。

如果你找不到这个脚本:

import win32evtlog
import win32api
import win32con
import win32security # To translate NT Sids to account names.

import win32evtlogutil

def ReadLog(computer, logType="Application", dumpEachRecord = 0):
    # read the entire log back.
    h=win32evtlog.OpenEventLog(computer, logType)
    numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
#       print "There are %d records" % numRecords

    num=0
    while 1:
        objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
        if not objects:
            break
        for object in objects:
            # get it for testing purposes, but dont print it.
            msg = win32evtlogutil.SafeFormatMessage(object, logType)
            if object.Sid is not None:
                try:
                    domain, user, typ = win32security.LookupAccountSid(computer, object.Sid)
                    sidDesc = "%s/%s" % (domain, user)
                except win32security.error:
                    sidDesc = str(object.Sid)
                user_desc = "Event associated with user %s" % (sidDesc,)
            else:
                user_desc = None
            if dumpEachRecord:
                print "Event record from %r generated at %s" % (object.SourceName, object.TimeGenerated.Format())
                if user_desc:
                    print user_desc
                try:
                    print msg
                except UnicodeError:
                    print "(unicode error printing message: repr() follows...)"
                    print repr(msg)

        num = num + len(objects)

    if numRecords == num:
        print "Successfully read all", numRecords, "records"
    else:
        print "Couldn't get all records - reported %d, but found %d" % (numRecords, num)
        print "(Note that some other app may have written records while we were running!)"
    win32evtlog.CloseEventLog(h)

def usage():
    print "Writes an event to the event log."
    print "-w : Dont write any test records."
    print "-r : Dont read the event log"
    print "-c : computerName : Process the log on the specified computer"
    print "-v : Verbose"
    print "-t : LogType - Use the specified log - default = 'Application'"


def test():
    # check if running on Windows NT, if not, display notice and terminate
    if win32api.GetVersion() & 0x80000000:
        print "This sample only runs on NT"
        return

    import sys, getopt
    opts, args = getopt.getopt(sys.argv[1:], "rwh?c:t:v")
    computer = None
    do_read = do_write = 1

    logType = "Application"
    verbose = 0

    if len(args)>0:
        print "Invalid args"
        usage()
        return 1
    for opt, val in opts:
        if opt == '-t':
            logType = val
        if opt == '-c':
            computer = val
        if opt in ['-h', '-?']:
            usage()
            return
        if opt=='-r':
            do_read = 0
        if opt=='-w':
            do_write = 0
        if opt=='-v':
            verbose = verbose + 1
    if do_write:
        ph=win32api.GetCurrentProcess()
        th = win32security.OpenProcessToken(ph,win32con.TOKEN_READ)
        my_sid = win32security.GetTokenInformation(th,win32security.TokenUser)[0]

        win32evtlogutil.ReportEvent(logType, 2,
            strings=["The message text for event 2","Another insert"],
            data = "Raw\0Data".encode("ascii"), sid = my_sid)
        win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE,
            strings=["A warning","An even more dire warning"],
            data = "Raw\0Data".encode("ascii"), sid = my_sid)
        win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE,
            strings=["An info","Too much info"],
            data = "Raw\0Data".encode("ascii"), sid = my_sid)
        print("Successfully wrote 3 records to the log")

    if do_read:
        ReadLog(computer, logType, verbose > 0)

if __name__=='__main__':
    test()

希望这个脚本能满足您的需求

关于python - 使用 pywin32(win32evtlog 模块)在 Python 中读取 Windows 事件日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30287121/

相关文章:

python - 良好做法默认值

python - 如何将 Tk 输入小部件上输入的值存储在变量中

windows - Windows文件模式中波浪号是什么意思

winapi - 为什么我们在使用ExitWindowsEx之前需要添加SE_SHUTDOWN_NAME权限

python - 在 Lion (OSX) 上安装 PyQt4 时出现问题

python - 整数字段前缀零不显示

python - python 上的 gensim Word2Vec 的不同模型

python - 用解包包装 Python for 循环的最佳方法是什么?

python 2.7 : difference between exit() and raise ValueError ("example")

perl - 如何在Windows中杀死进程树