读取特定 Windows 事件日志事件

新手上路,请多包涵

我正在开发一个程序,需要知道如何根据记录号读取 Windows 事件日志的特定条目,该脚本已经具有该记录号。下面是我一直在使用的代码,但我不想遍历所有事件,直到找到我正在寻找的事件。有任何想法吗?

 import win32evtlog

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

while True:
    events = win32evtlog.ReadEventLog(hand, flags,0)
    if events:
        for event in events:
            if event.EventID == "27035":
                print 'Event Category:', event.EventCategory
                print 'Time Generated:', event.TimeGenerated
                print 'Source Name:', event.SourceName
                print 'Event ID:', event.EventID
                print 'Event Type:', event.EventType
                data = event.StringInserts
                if data:
                    print 'Event Data:'
                    for msg in data:
                        print msg
                break

原文由 Zac Brown 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

不!没有可用的函数允许您根据事件 ID 获取事件。

参考: 事件记录函数

GetNumberOfEventLogRecords  Retrieves the number of records in the specified event log.
GetOldestEventLogRecord     Retrieves the absolute record number of the oldest record
                            in the specified event log.
NotifyChangeEventLog        Enables an application to receive notification when an event
                            is written to the specified event log.

ReadEventLog                Reads a whole number of entries from the specified event log.
RegisterEventSource         Retrieves a registered handle to the specified event log.

只有其他感兴趣的方法是读取最旧的事件。

您将不得不以任何方式迭代结果,并且您的方法是正确的:)

您只能像下面这样更改方法的形式,但这是不必要的。

 events = win32evtlog.ReadEventLog(hand, flags,0)
events_list = [event for event in events if event.EventID == "27035"]
if event_list:
    print 'Event Category:', events_list[0].EventCategory

这与您所做的方式相同,但更简洁

原文由 pyfunc 发布,翻译遵循 CC BY-SA 3.0 许可协议

我意识到这是一个老问题,但我遇到了它,如果我遇到了,其他人也可能遇到。

您还可以编写自定义查询,这样您就可以通过编写脚本的任何 WMI 参数(包括事件 ID)进行查询。它还具有让您提取并清除所有那些在那里的 VBS WMI 查询的好处。实际上,我比其他任何人都更频繁地使用此功能。有关示例,请参阅:

下面是在应用程序日志中查询特定事件的示例。我还没有充实它,但您也可以构建一个 WMI 时间字符串并查询特定日期/时间之间或之后的事件。

 #! py -3

import wmi

def main():
    rval = 0  # Default: Check passes.

    # Initialize WMI objects and query.
    wmi_o = wmi.WMI('.')
    wql = ("SELECT * FROM Win32_NTLogEvent WHERE Logfile="
           "'Application' AND EventCode='3036'")

    # Query WMI object.
    wql_r = wmi_o.query(wql)

    if len(wql_r):
        rval = -1  # Check fails.

    return rval

if __name__ == '__main__':
    main()

原文由 Deacon 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题