In Python, we can read user input and detect hardware devices like a keyboard and mouse to develop interactive applications. In particular, the
pynput module allows us to work with such devices and detect keypress and cursor movement with functions.
This tutorial will demonstrate how to create a keylogger in Python.
Create a Keylogger in Python
First, let us understand what a keylogger is. A keylogger is an application that can read the keys pressed by the user on the keyboard and store these in a log file.
Such applications are generally used to monitor devices for troubleshooting and detecting technical issues. These days, such scripts are used for malicious intent, like monitoring devices to see the password and other access codes, so one should be careful about using these scripts.
We will now create a simple keylogger in Python using the
We will use the
logging module to create a log file that tracks all the keys pressed. We will create a file using the
basicConfig() constructor and specify the
format within this constructor.
pynput module has a
Listener object that collects functions when a key is pressed. We will define a function called
press which the
Listener object will collect.
press() function will read the keys pressed and log them into the file using the
logging.info() function. Note that the key will need to be typecast into a string first.
from pynput.keyboard import Key, Listener
filename=("logfile.txt"), level=logging.DEBUG, format="%(asctime)s: %(message)s"
with Listener(on_press=press) as listener:
As shown in the above example, when the given script is running, the keys pressed by the user are noted in the log file. Note that every entry in the log file is based on the format specified in the