As Easy as Pie: Building a Simple Keylogger in Python
This small article will show you how quickly and easily create a small and very simple keylogger in Python. This keylogger will consist of eight lines of code - but it works!
For our keylogger, we are going to use a python library called pynput (you can find it here: https://github.com/moses-palmer/pynput). Install it using pip package manager.
Create a file, name it keylogger.pyw, launch any text editor - and let’s start creating the keylogger.
from pynput.keyboard import Key, Listener
logdir = ""
logging.basicConfig(filename = (logdir"logfile.txt"),level = logging.DEBUG, format = '%(asctime)s : %(message)s')
with Listener(on_press = keypress) as listener:
That’s all. Just eight lines. Here is what each line is for:
The first one is all about importing the packages (in our case - pynput) and logging, so that each key will be logged when pressed.
Next, we need a logging directory, which in this case is set to empty (but you can specify your own), so it is located in the same directory as the script.
The next line deals up with the logging configurations, in which the code is self-explanatory. The basicConfig() method takes has three parameters, one of which is filename. After it, we have a key press listener method – it will be logging the respective key after it has been pressed. So, each keystroke will be logged.
As you have probably noticed, we saved the source file with a .pyw extension rather than .py one. The reason is that in this case the keylogger can run at the background, because the code in .pyw can be run without creating a console window. Just run the code, press some keys randomly and make sure all those keys being logged on to the file you specified. It means that you have just created a keylogger in Python, consisting of 8 lines of code!