Reading Windows event logs of the last one hour using win32evtlog module

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To read Windows event logs of the last one hour using the win32evtlog module in Python, you can follow these steps:

  1. Install the pywin32 package, which includes the win32evtlog module, if you haven't already. You can install it using pip:

    pip install pywin32
  2. Import the required modules and define the function to read event logs:

    python
    import win32evtlog
    import win32evtlogutil
    import win32con
    import datetime

    def read_events_last_hour(log_type, log_source):
    # Get the current time
    end_time = datetime.datetime.now()

    # Calculate the start time as one hour before the current time
    start_time = end_time - datetime.timedelta(hours=1)

    # Connect to the event log
    hand = win32evtlog.OpenEventLog(None, log_source)

    # Define the event filter to get events in the specified time range
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEEK_READ
    events = win32evtlog.ReadEventLog(hand, flags, 0)

    # Read the events
    event_list = []
    while True:
    events = win32evtlog.ReadEventLog(hand, flags, 0)
    if not events:
    break
    for ev_obj in events:
    timestamp = win32evtlogutil.EvtFormatMessageTime(ev_obj.TimeGenerated)
    if start_time <= timestamp <= end_time:
    event_list.append(ev_obj)

    win32evtlog.CloseEventLog(hand)

    return event_list

    # Example usage
    log_type = 'System'
    log_source = 'Microsoft-Windows-Kernel-General'
    events = read_events_last_hour(log_type, log_source)

    for event in events:
    print(f"Event Category: {event.EventCategory}")
    print(f"Event ID: {event.EventID}")
    print(f"Event Type: {event.EventType}")
    print(f"Event Time: {win32evtlogutil.EvtFormatMessageTime(event.TimeGenerated)}")
    print(f"Event Description: {win32evtlogutil.SafeFormatMessage(event, log_type)}")
    print("=" * 80)

This script defines a function called read_events_last_hour, which connects to the specified event log, reads events from the last one hour, and returns the list of events in that time range. The example usage section demonstrates how to call the function to read events from the "System" log with the source "Microsoft-Windows-Kernel-General." You can modify the log_type and log_source variables to read events from different event logs.