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

问题描述 投票:0回答:1

我正在开发一个需要在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(最近一次调用最后一次):

文件“”,第1行,in

notify = win32evtlog.NotifyChangeEventLog(hand,1)

错误:(6,'NotifyChangeEventLog','句柄无效。')

有什么参数?

python windows wmi event-log pywin32
1个回答
1
投票

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

根据[MS.Docs]: NotifyChangeEventLog functionwin32evtlog.NotifyChangeEventLog包裹):

hEvent

手动重置或自动重置事件对象的句柄。使用CreateEvent函数创建事件对象。

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

code.朋友:

#!/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()

笔记:

  • 出于演示目的,我使用“系统”事件日志,因为有一种生成事件的简单方法 转到“服务”,选择一个(最好是一个未运行的),并更改其“启动类型”。单击“应用”时,将生成一个事件,该事件将生成脚本的输出。 最后,不要忘记撤消更改
  • 有关阅读日志事件的详细信息,请查看[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
© www.soinside.com 2019 - 2024. All rights reserved.