Search code examples
pythonpynput

activate keylogger with the press of a key and have it running for a set amount of time


I want to have a keylogger which is activated with the press of a key (any key) and then saves all keys pressed within a set amount of time (e.g. 10 sec.) in a list which is then printed. I tried this:

from pynput import keyboard
from time import sleep

def on_press(key):
    global recording, keys_pressed
    if not recording:
        recording = True
        sleep(10)
        print(" ".join(keys_pressed))
        recording = False


listener = keyboard.Listener(
    on_press=on_press)
listener.start()


def on_release(key):
    global recording
    if recording:
        print("key pressed")
        global keys_pressed
        Key = str(key)
        if Key.startswith("Key."):
            keys_pressed.append(Key[4:].strip("'"))
        else:
            keys_pressed.append(str(key).strip("'"))

listener2 = keyboard.Listener(
    on_release=on_release)
listener2.start()

keys_pressed = []

recording = False

while True:
    pass

It kinda works but it prints the list multiple time which I obviously don't want. The program runs also extremely slow.

If you know any Solutions please let me know.


Solution

  • it prints the list multiple time which I obviously don't want

    You are explicitly asking it to print the list each time a button is pressed here

    print(" ".join(keys_pressed))
    

    Furthermore, I cannot understand why you are trying to implement 2 listeners???

    I would do something more like this, although I'm sure there is still a more beautiful solution out there!

    from pynput import keyboard
    from time import time
    
    my_log = []
    started = False
    start_time = time() # just here to initialize, won't be used until started = True
    
    def on_press(key):
        global started
        global start_time
        if started is False:
            started = True
            start_time = time()
            print("starting timer")
        try:
            character = '{0}'.format(key.char)
        except AttributeError:
            character = '{0}'.format(key)
        my_log.append(character)
    
    
    def listen():
        global started
        print('keyboard listener is initialized')
        with keyboard.Listener(on_press=on_press):
            while True:
                if started:
                    now = time()
                    if now - start_time > 10:
                        break
            return # end our listener
    
    listen()
    print("done listening")
    print(my_log)
    

    Where an example output would look like (a bit messy because prints combine with what is typed):

    keyboard listener is initialized
    astarting timer
    bcdefghijklmnopqrstuvwxyzdone listening
    ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']