How Hackers Build Keyloggers in Python

BLOGS

Winston.I

6/21/20252 min read

A keylogger might sound like a high-tech surveillance tool, but it can be written in less than 15 lines of Python. Hackers use them to silently capture everything a victim types — from passwords to private messages. What makes a keylogger dangerous is its invisibility: it runs quietly in the background, logging each keystroke without displaying anything on-screen. These tools are often used in phishing payloads, USB drop attacks, or insider threats. In this post, we’ll walk through how attackers use the pynput library to build and run one. We’ll also explore how you can spot and defend against them.

At the heart of the attack is a listener that detects every keypress and writes it to a log file. The attacker starts by importing keyboard.Listener, then adds logging to write each key event with a timestamp. This makes it easier to track exactly what the victim was doing at any time — like typing their email, password, or a sensitive message. The script is launched silently using &, so it runs in the background. While it operates, it continuously appends each key to a file like keylog.txt. A quick check with tail shows every captured character — no alerts, no noise, just silent logging.

This type of keylogger can run for days, collecting thousands of keystrokes. Below is a real demonstration of what the attacker’s terminal looks like after launching the script and checking the output.

What’s Happening in the Screenshot

First, the attacker opens the keylogger script in nano, and you can see it now uses Python’s logging module for better timestamps and formatting. After saving the script, they run it with python3 keylogger.py &, placing it in the background. Then, using tail -n 10, they inspect the last 10 lines of the log. Each line shows a timestamp, along with the key pressed — for example: h, a, c, k, i, n, g, , t, e. This shows that someone typed “hackingte” — proof that the logger is working and silently recording keystrokes in real time.

🔐 How to Defend Against Python Keyloggers

Keyloggers rely on user inattention. Always be wary of .py, .exe, or .bat files received over email or messaging apps. Use endpoint protection tools that monitor Python processes or detect hooks on input devices. Enable Two-Factor Authentication so even a stolen password isn’t enough. Regularly audit files like keylog.txt or monitor logs being written to hidden directories. If you’re building secure systems, lock down access to Python runtime environments entirely on production endpoints.