As you guys all know python is a pretty powerful language which can be utilized for any purpose. And so in this article I would like to make you an even big fan of python by building a simple keylogger with just a few lines of code.
So lets get started. First of all in case you are not aware key-logger is a a computer program that records every keystroke made by a computer user, especially in order to gain fraudulent access to passwords and other confidential information. With that being said lets proceed. We will be using a python library known as pynput which helps us to achieve what is intended. Just install it with the pip package manager i,e pip install pynput
which does the job for you. Alright done with the installation.
Create a file named keylogger.pyw
(name it anything as you like but don’t forget about the pyw extension), fire up your favourite text editor and we are ready to write our key-logger.
from pynput.keyboard import Key, Listener
import logging
log_directory = “”
logging.basicConfig(filename = (log_director“log_results.txt”),level = logging.DEBUG, format = ‘%(asctime)s : %(message)s’)
def keypress(Key):
logging.info(str(Key))
with Listener(on_press = keypress) as listener:
listener.join()
Refer the GitHub-Gist
This is the whole code. Now I’ll explain what each line does. The first line is all about importing the required packages in our case pynput
and logging for the purpose of logging each key when pressed. Then we should provide a logging directory which is set to empty in this case so that it resides in the same directory as the script lies. Next line deals up with the logging configurations in which the code is self explanatory. The basicConfig()
function takes in three parameters where the filename can be provided. After which we have the key press listener method which does nothing other than logging the respective key that has been pressed. At last we have the listener part for each keystroke.
Hope you have noticed that we saved the source file with a .pyw
extension other than the normal .py
extension. The reason is because a key-logger is intended to serve its purpose in the background, pyw
runs the code without creating a console window. Just run the code, press some keys randomly and notice all those keys being logged on to the file as specified. Interesting isn’t it? We made a key-logger within just 15 lines of code in python. To kill the process fire up task manager and kill the python process. There you go :)
Top comments (0)