Archive
Posts Tagged ‘keylogger’
simple keylogger
November 16, 2019
Leave a comment
I was working on a console application and I wanted to add the functionality to listen to keyboard presses in an infinite loop. I used the pynput library and tried this basic code that I found on the project’s web site:
# pip3 install pynput xlib
# xlib is required for mouse support
from pynput.keyboard import Key, Listener
def on_press(key):
print("{0} pressed".format(key))
def on_release(key):
print("{0} release".format(key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
It worked well. I let it run and switched to another window when I noticed that the script was still monitoring what keys I press, though I was in another window! So it monitors the keyboard globally. And, under Linux, I didn’t even have to start it with sudo.
So, if you need a simple keylogger, here it is :) You don’t need to add much to the code above to have a working keylogger.
Update (20240204):
Here is a slightly longer example:
from pynput.keyboard import Key, Listener
def on_press(key):
print("{0} pressed".format(key))
if key == Key.esc:
print("# you pressed ESC")
try:
if key.char == "a":
print("# you pressed 'a'")
#
except:
pass
def on_release(key):
print("{0} release".format(key))
print("---")
def main():
print("keylogger running...")
with Listener(on_press=on_press, on_release=on_release) as listener:
try:
listener.join()
except KeyboardInterrupt:
print()
if __name__ == "__main__":
main()
Python keylogger
August 2, 2013
2 comments
