如何通知特定的 windows 日志事件?

How to notify a specific windows log event?

我正在开发一个需要在 windows 事件日志中通知特定事件的程序。我不知道需要在 NotifyChangeEventLog() 函数中指定的参数。

下面是我一直在使用的代码:

import win32evtlog 

server = 'localhost' # name of the target computer to get event logs
logtype = 'Application' # 'Application' # 'Security'
hand = win32evtlog.OpenEventLog(server,logtype)
flags = 
win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
total = win32evtlog.GetNumberOfEventLogRecords(hand)
print total
notify = win32evtlog.NotifyChangeEventLog(hand, 1)

我收到这个错误:

notify = win32evtlog.NotifyChangeEventLog(hand, 1)

Traceback (most recent call last):

File "", line 1, in

notify = win32evtlog.NotifyChangeEventLog(hand, 1)

error: (6, 'NotifyChangeEventLog', 'The handle is invalid.')

参数是什么?

您找到了 1st 参数,它是一个打开的事件日志的句柄。

根据 [MS.Docs]: NotifyChangeEventLog functionwin32evtlog.NotifyChangeEventLog 换行):

hEvent

A handle to a manual-reset or auto-reset event object. Use the CreateEvent function to create the event object.

所以,你需要这样的东西。

code.py:

#!/usr/bin/env python3

import sys
import win32evtlog
import win32event
import win32api
import win32con
import msvcrt


def main():
    server = None # "localhost" # name of the target computer to get event logs
    source_type = "System" # "Application" # "Security"
    h_log = win32evtlog.OpenEventLog(server, source_type)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(h_log)
    print(total)
    h_evt = win32event.CreateEvent(None, 1, 0, "evt0")
    win32evtlog.NotifyChangeEventLog(h_log, h_evt)
    print("Waiting for changes in the '{:s}' event log. Press a key to exit...".format(source_type))
    while not msvcrt.kbhit():
        wait_result = win32event.WaitForSingleObject(h_evt, 500)
        if wait_result == win32con.WAIT_OBJECT_0:
            print("The '{:s}' event log has been modified".format(source_type))
            # Any processing goes here
        elif wait_result == win32con.WAIT_ABANDONED:
            print("Abandoned")

    win32api.CloseHandle(h_evt)
    win32evtlog.CloseEventLog(h_log)


if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()

备注:

  • 出于演示目的,我使用“System”事件日志,因为有一种生成事件的简单方法
    • 转到“服务”,选择一个(最好不是运行),然后更改其“启动类型”。单击“Apply”时,将生成一个事件,该事件又会从脚本中生成输出。
      最后不要忘记撤消更改
  • 有关读取日志事件的详细信息,请查看

输出:

(py27x64_test) e:\Work\Dev\Whosebug\q051036392>"e:\Work\Dev\VEnvs\py27x64_test\Scripts\python.exe" code.py
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32

3430
Waiting for changes in the 'System' event log. Press a key to exit...
The 'System' event log has been modified
The 'System' event log has been modified