Building A KeyLogger Using Python For Fun And Learning Purpose

Building A KeyLogger Using Python For Fun And Learning Purpose

Keylogger are very basic form of malware but still effective and a threat actor. If you are creative enough then you can make it more sophisticated and useful. Here I am sharing a basic Keylogger-making process for offensive security practice. (Learning purpose only).

In the wild, there are a lot of Python libraries. PyWinHook is one of the most effective ones. PyWinHooks enables us to easily capture all keyboard events. It actually takes advantage of the native Windows function SetWindwosHookEx. PyWinHook will take care of all Windows keyboard capturing functions which are low-level programming for attackers like us. I am not going to explain each line here but definitely I will explain each function's job in this code.


Lets open vs code and create your "keylogger.py"

First import all necessary libraries.


Article content
Necessary Python Libraries For KeyLogger

  • ctypes is a Python library used for interacting with dynamic libraries (DLLs) in a platform-independent way.
  • io.StringIO provides an in-memory stream for string-based I/O operations.
  • os provides operating system-related functionalities.
  • pythoncom is a module for interacting with COM (Component Object Model) objects in Python.
  • pyWinhook is a library for setting up and managing low-level Windows keyboard and mouse hooks.
  • sys provides access to some variables used or maintained by the Python interpreter.
  • time provides various time-related functions.
  • win32clipboard is a module for accessing the Windows clipboard


Then we will declare a variable. Which will contain an integer which is the time in seconds the keylogger will run.


Article content
Variable TIMEOUT

This keylogger will run for 100 seconds.

Then we will create a class for the keylogger.


Article content
Class KeyLogger

  • KeyLogger is a class that represents the keylogger.
  • __init__ is the constructor method that initializes the current_window attribute to None. This attribute will store the name of the currently focused window.


Article content
The function to get the current process

  • get_current_process retrieves information about the currently focused window and its associated process.
  • It uses various Windows API functions from windll.user32 and windll.kernel32 to achieve this.
  • It gets the handle of the foreground window using GetForegroundWindow().
  • It retrieves the process ID and executable name using GetWindowThreadProcessId() and GetModuleBaseNameA() respectively.
  • The window title is retrieved using GetWindowTextA().
  • The current_window attribute is updated with the decoded window title.
  • The gathered information is printed on the console.
  • The OpenProcess() and CloseHandle() functions are used to work with the process handle.

[Note: This function is inside the class KeyLogger.]


Article content
Function to capture key strokes from keyboard

  • mykeystroke is a callback function that is triggered whenever a key is pressed.
  • It checks if the focused window has changed and calls get_current_process() if needed.
  • If the ASCII value of the key is between 32 and 127, it prints the corresponding character.
  • For special keys, like 'V' (for paste), it uses win32clipboard to retrieve clipboard data.
  • The function returns True to indicate that the key event should continue propagating.

[Note: This function is inside the class KeyLogger.]



Article content
It's the run loop

  • run is the main function that sets up and runs the keylogger.
  • It temporarily redirects the standard output (sys.stdout) to an in-memory string buffer using StringIO.
  • An instance of KeyLogger is created.
  • A HookManager instance hm is created from pyHook to manage the keyboard hook.
  • The KeyDown event of the hook manager is set to the mykeystroke callback.
  • The keyboard hook is initiated with HookKeyboard().
  • The function enters a loop that captures keyboard events and updates the log.
  • The loop runs until the timeout specified TIMEOUT is reached.
  • During each iteration, pythoncom.PumpWaitingMessages() ensure that Windows messages are processed.
  • Captured data is collected from the redirected standard output and added to the log.
  • The buffer is then cleared and reset for the next iteration.
  • Once the loop finishes, the standard output is restored, and the log is returned.

[Note: It's outside the KeyLogger class]



Article content
The Main Function

  • This block checks if the script is being run as the main program.
  • It calls the run() function to start capturing keystrokes and retrieving information about windows and processes.
  • The captured log is then written to a file named 'keylog1.txt'.


Finally, we have built the KeyLogger. Now just open a command prompt as administrator. Then run the Python file.

[Note: This is an Idea how what a keylogger looks like. It's not a proper KeyLogger. You need to use your creative brain to make it perfect.]

You will need to install some libraries. Use Google to install them. If I get enough responses I might write more. Thanks.

For Source Code Connect, Repost, and DM.

Thanks to Jobyer Ahmed Sir for help.


Thanks for detailed note it helps a lots

Like
Reply

Does this get detected ?

Like
Reply

To view or add a comment, sign in

Others also viewed

Explore content categories