尝试使用 Windows 事件日志 (System) 计算每天的总 Windows 运行时间

Trying to calculate total windows uptime for each day using the Windows Event Log (System)

提问人:Omar Ahmed 提问时间:6/23/2023 更新时间:6/23/2023 访问量:37

问:

我正在尝试通过分析 Windows 事件日志记录来计算系统的正常运行时间。目标是确定系统在特定日期范围内运行(即未关闭)的持续时间。

代码尝试读取 Windows 事件日志文件并循环访问事件记录。它标识指示系统启动和关闭事件的特定事件 ID。通过比较这些事件及其时间戳,它可以计算连续系统启动和关闭事件之间的持续时间。

问题是代码在某些时候失败并存在逻辑缺陷,似乎我没有足够的系统代码知识来提取必要的数据。

目标是创建一个表格,其中显示以下内容:-

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...

我所在位置的代码片段:-

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()}")

代码输出以下内容:-

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

这在计算或使用事件代码方面显然是错误的。

注意:我没有导出安全日志的管理员权限

Python Windows 事件日志 正常运行时间

评论


答: 暂无答案