This code defines and implements a Windows Service (named "LionService")...

August 25, 2025 at 09:27 AM

import os import psutil import servicemanager import socket import sys import win32event import win32service import win32serviceutil import win32timezone from datetime import datetime class LionService(win32serviceutil.ServiceFramework): _svc_name_ = "LionService" _svc_display_name_ = "This is the Lion Service" # _svc_description_ = def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaultimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): rc = None while rc != win32event.WAIT_OBJECT_0: # write current date, time, CPU usage, memory usage, and running process IDs to a file current_datetime = datetime.now() current_date = current_datetime.date() current_time = current_datetime.time() cpu_usage = psutil.cpu_percent(interval=1) # compares system CPU times elapsed before and after interval memory_usage = psutil.virtual_memory() running_pids = psutil.pids() if os.path.exists('C:\\temp\\LionService.log'): with open('C:\\temp\\LionService.log', 'a') as f: f.write('Lion service running...\n') f.write(f"Date: {str(current_date)}\n Time: {str(current_time)}\n CPU Usage: {int(cpu_usage)}\n Memory Usage: {memory_usage}\n Running PIDs: {running_pids}\n") f.write('---------------------------------------------------------------------------------------------------') rc = win32event.WaitForSingleObject(self.hWaitStop, 10000) else: with open('C:\\temp\\LionService.log', 'w') as f: f.write('Lion service running...\n') f.write(f"Date: {str(current_date)}\n Time: {str(current_time)}\n CPU Usage: {int(cpu_usage)}\n Memory Usage: {memory_usage}\n Running PIDs: {running_pids}\n") f.write('---------------------------------------------------------------------------------------------------') rc = win32event.WaitForSingleObject(self.hWaitStop, 10000) def main(): if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(LionService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(LionService) if __name__ == '__main__': main()

This code defines and implements a Windows Service (named "LionService") in Python using the pywin32 library. Here's what the code does:

1. Definition and Initialization

  • The LionService class inherits from win32serviceutil.ServiceFramework, which is required to implement a Windows Service.
  • The _svc_name_ is the internal name of the service.
  • The _svc_display_name_ is the display name of the service in the Windows Services Manager.

2. Service Initialization

  • In the __init__ method, a stop event (self.hWaitStop) is created using win32event.CreateEvent to monitor when the service should stop.
  • socket.setdefaultimeout(60) defines a default timeout for socket operations (though sockets are not used explicitly in the provided code).

3. Stopping the Service

  • The SvcStop method is executed when the service is stopped. This signals the service (self.hWaitStop) to terminate gracefully by setting the stop event (win32event.SetEvent).

4. Running the Service

  • The SvcDoRun method runs the service's main loop.
  • The method repeatedly collects system information and writes it to a log file (C:\temp\LionService.log) until the stop event self.hWaitStop is triggered.

5. What Information is Logged?

Inside each iteration of the loop:

  • The current date and time are recorded using datetime.now().
  • The system's current CPU usage percentage is retrieved using psutil.cpu_percent(interval=1).
  • Memory usage details are retrieved using psutil.virtual_memory().
  • A list of all running PIDs (Process IDs) is retrieved using psutil.pids().
  • The retrieved information is written to the file:
    • If the file exists, it appends new data.
    • If the file does not exist, it creates the file and writes the information.
  • After writing the data, the code waits for 10 seconds (win32event.WaitForSingleObject) before performing the next iteration.

6. Main Function

  • If the script is run without any command-line arguments, it initializes and runs the service using the pywin32 service dispatcher (servicemanager).
  • If there are command-line arguments, it uses win32serviceutil.HandleCommandLine to process them (e.g., commands like install, start, or stop the service).

7. Output

The service continuously runs (until stopped) and logs the following information into the file C:\temp\LionService.log:

  • The current date.
  • Current time.
  • CPU usage percentage.
  • Memory usage statistics.
  • A list of all running process IDs (PIDs).

8. Stopping Point

  • The main loop continues running, collecting and logging data, with a 10-second wait between iterations.
  • When the service receives the stop signal, the SvcStop method is called, and the stop event (hWaitStop) is set, exiting the loop and stopping the service.

Summary

This script defines a custom Windows Service that periodically logs system metrics (CPU, memory, running processes) into a file (C:\temp\LionService.log). It collects this data every 10 seconds and appends it to the log file. The service can be started, stopped, installed, or uninstalled using standard Windows Service controls or the win32serviceutil command-line interface.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node