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

2024-04-16 11:57:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个需要在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.')

参数是什么?在


Tags: 函数程序read参数serverapplicationwindows事件
1条回答
网友
1楼 · 发布于 2024-04-16 11:57:39

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

根据[MS.Docs]: NotifyChangeEventLog function(即win32evtlog.NotifyChangeEventLog包装):

hEvent

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

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

代码.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”时,将生成一个事件,该事件将从脚本生成输出。
      最后,不要忘记撤消更改
  • 有关读取日志事件的详细信息,请选中[SO]: Converting Python win32evtlog objects to xml (@CristiFati's answer)

输出

(py27x64_test) e:\Work\Dev\StackOverflow\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

相关问题 更多 >