0

I am trying to calculate the uptime of a system by analyzing Windows Event Log records. The goal is to determine the duration for which the system was operational (i.e., not shut down) on specific date range.

The code attempt reads the Windows Event Log file and iterates through the event records. It identifies specific event IDs that indicate system start and shutdown events. By comparing these events and their timestamps, it calculates the duration between consecutive system start and shutdown events.

Issue is that the code fails at some point with a logic flaw it seems like I don't have enough knowledge with system codes to use to extract the necessary data.

Goal is to create a table where it shows the following:-

01/05/2023    8.5 Hours
02/05/2023    9.2 Hours
03/05/2023    6.1 Hours
04/05/2023    7.3 Hours
05/05/2023    10.2 Hours
etc...

Code snippet to where I am at:-

import os
from datetime import datetime, timedelta
from evtx import PyEvtxParser
from bs4 import BeautifulSoup

def get_uptime(start_date, end_date):
    start_date = datetime.strptime(start_date, '%m/%d/%Y').date()
    end_date = datetime.strptime(end_date, '%m/%d/%Y').date()
    uptime_dict = {}

    log_file = r'system.evtx'
    parser = PyEvtxParser(log_file)
    last_shutdown_time = None

    for record in parser.records():
        event_time_str = record['timestamp']
        event_time = datetime.strptime(event_time_str, '%Y-%m-%d %H:%M:%S.%f %Z')
        event_date = event_time.date()

        if event_date < start_date:
            continue
        elif event_date > end_date:
            break

        # Extract the 'EventID' from the 'record' dictionary
        data = record['data']
        soup = BeautifulSoup(data, 'xml')
        event_id = int(soup.find('EventID').text)

        if event_id == 6005:
            # System start event
            last_shutdown_time = event_time
        elif event_id == 6006:
            # System shutdown event
            if last_shutdown_time is not None:
                uptime_duration = event_time - last_shutdown_time
                uptime_dict[event_date] = uptime_dict.get(event_date, timedelta()) + uptime_duration

    return uptime_dict


# Specify the start and end dates
start_date = '05/01/2023'
end_date = '06/01/2023'

# Get the uptime data
uptime_dict = get_uptime(start_date, end_date)

# Print the uptime for each day
print("Date\t\tUptime")
for date, uptime in uptime_dict.items():
    print(f"{date}\t{uptime.total_seconds()}")

Code outputs the following:-

Date        Uptime

2023-05-03  -34522.473358
2023-05-11  -33302.944477
2023-05-15  -37.82539
2023-05-16  -73.404957
2023-05-20  -169.323921
2023-05-21  -38.657968
2023-05-26  -40.874938

Which is clearly wrong with the calculations or the use of Event codes.

N.B I don't have admin privileges to export security log

Omar Ahmed
  • 139
  • 8

0 Answers0