-1

I am new to python and I'm trying to imitate a keylogger. I want when I press backspace key, it will delete the last character in the text file, like type "helli", the letter "i" was wrong and I press backspace, the "i" letter is deleted. Anyone have an idea?

from pynput.keyboard import Listener

def anonymous(key):
    key = str(key)
    key = key.replace("'","")
    if key == "Key.esc":
        raise SystemExit(0)
    if key == "Key.ctrl_l":
        key = "ctrl"
    if key == "Key.enter":
        key = "\n"
    if key == "Key.caps_lock":
        key = "capslock"
    if key == "Key.tab":
        key = "\n"
    if key == "Key.ctrl_r":
        key = "ctrl"
    if key == "Key.space":
        key = " "
    if key == "Key.backspace"
#this line

    with open("log.txt", "a") as file:
        file.write(key)
    print(key)

with Listener(on_press=anonymous) as listener:
    listener.join()

1 Answers1

0

I can't answer specifically for python.

Basically, once you have a written a character to a file it is gone.

  • You can write a different character at the same offset (seek to the correct location) and write in the next character the user types,
  • or you could record the backspace character, and replay it?
  • or you could seek back and record a dummy character that your reader knows to ignore - though this has no advantages over recording backspace, especially if your dummy is a long utf8 sequence.
  • record whole lines with all corrections only after enter was pressed?

Generally the first or last option is good enough. The user has to press enter to complete a command usually, so the enter will overwrite 1 rubbish character. If you are doing something where enter is not ubiquitous, then are you sure backspace actually means erase? Imagine someone uses arrow keys to scroll a web page then presses backspace to go back a page?

Speaking of utf8, are you sure you know what the "last character" means?

In linux there is also a truncate() method that can be used to resize a file. Most languages don't expose that at the language level, though, and getting the low-level file descriptor methods to play nice with high level soft buffered files can be complicated. You could use this at the end of your code if you still had some characters that had not been overwritten.

Gem Taylor
  • 5,381
  • 1
  • 9
  • 27