Writing a Keylogger with Python


In today’s world, where technology is rapidly advancing, information and network security have become more crucial than ever. This article aims to delve into basic computer security concepts and learn how keyboard inputs can be monitored for educational purposes by writing a keylogger. Keyloggers are tools that record all inputs made by a user through the keyboard. While they have a notorious reputation for malicious use, when used safely for educational purposes, these tools can provide in-depth knowledge on security and explore methods of protection.

What is PynPut and Why Use It?

The pynput library is a powerful tool in Python that allows you to monitor and control keyboard and mouse events. It can listen to, record, and simulate keyboard keystrokes and mouse movements. The flexibility of pynput makes it perfect for those looking to monitor user interactions, write automated tests, or develop security tools for educational purposes. (Cybersecurity with Python: A Comprehensive Roadmap)

Installing the Required Library

Before starting our project, we need to install the pynput library. This can easily be done with the following pip command:

$ pip3 install pynput
Keyboard Listener

To listen to keyboard events, you can use the Listener class. The example below captures inputs from the keyboard and prints every keystroke to the console:

from pynput.keyboard import Key, Listener

def on_press(key):
        print(f'Alphanumeric key pressed: {key.char}')
    except AttributeError:
        print(f'Special key pressed: {key}')

def on_release(key):
    print(f'Key released: {key}')
    if key == Key.esc:
        # Stop listening when ESC key is pressed
        return False

# Start listening to keyboard events with Listener
with Listener(on_press=on_press, on_release=on_release) as listener:
Mouse Listener

To listen to mouse events, you can use the pynput.mouse.Listener class as well. The example below tracks mouse movements and clicks:

from pynput.mouse import Listener

def on_move(x, y):
    print(f'Mouse moved to ({x}, {y})')

def on_click(x, y, button, pressed):
    if pressed:
        print(f'Mouse clicked at ({x}, {y}) with {button}')
        print(f'Mouse released at ({x}, {y}) with {button}')

def on_scroll(x, y, dx, dy):
    print(f'Mouse scrolled at ({x}, {y}) with delta ({dx}, {dy})')

# Start listening to mouse events with Listener
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:

These code examples demonstrate the basic usage of the pynput library. Understanding how to use the Listener classes to monitor keyboard and mouse events can help you when developing more complex programs, especially when you want to monitor user interactions or write automated tests. (Understanding Encapsulation in Programming)

Creating a Keylogger with Python


This section will cover how to develop a simple application using Python to monitor keyboard activities and process this data. Our goal is to demonstrate how to safely record keyboard inputs for educational and research purposes using the tools provided by the pynput library.

Step 1: Creating the KeyLogger Class

We will start by creating a SimpleKeyLogger class in Python. This class will listen to keyboard events and process specific keystrokes.

from pynput.keyboard import Key, Listener

class SimpleKeyLogger:
    def __init__(self):
        self.listener = Listener(on_press=self.on_press, on_release=self.on_release)

    def on_press(self, key):
        # Capture and process specific keys

    def on_release(self, key):
        # Terminate the keylogger with the ESC key

    def start(self):

    def join(self):
Step 2: Capturing Keystrokes

The primary purpose of our keylogger is to capture user keystrokes and process them. We can fill the on_press method as follows:

def on_press(self, key):
        # Capture keystrokes and print to the console
        if key ==
            print(' ', end='', flush=True)
        elif key ==
            print('    ', end='', flush=True)
        elif key == Key.enter:
            print('\n', end='', flush=True)
        elif key == Key.backspace:
            print('\b \b', end='', flush=True)
        elif hasattr(key, 'char') and key.char:
            # Print alphanumeric characters
            print(key.char, end='', flush=True)
Step 3: Terminating the Keylogger

We want our keylogger to terminate when the user presses the ESC key. We can update the on_release method as follows:

def on_release(self, key):
        # Terminate the keylogger when ESC key is pressed
        if key == Key.esc:
            return False  # This will stop the Listener loop
Step 4: Starting the Keylogger

To test our keylogger, we can use the following code:

key_logger = SimpleKeyLogger()


This article has explored the basics of developing a simple keylogger using Python. By leveraging the power of the pynput library, we discovered how to monitor keyboard and mouse events and process these data. Tools like these can deepen our understanding of computer security and equip us with practical skills in network security, data protection, and system monitoring

Leave a Comment

Join our Mailing list!

Get all latest news, exclusive deals and academy updates.