使用pynput.Listener和keylogger监听特定的键?

时间:2020-01-02 16:39:53

标签: python listener keylogger pynput

我下面有以下python脚本:

但是我想“监听”,或者如果足够的话,只需将以下键“记录”到我的log.txt中:Key.left和Key.up。我该如何造成这种限制?

question类似,但是她的回复的代码结构有些不同,可能需要进行重大更改以允许键盘记录程序和对此Listener的限制。

另外question在我看来可能是寻找解决方法的灵感之源。

我花了一些时间寻找可以给我这个答案或可以帮助我思考的问题,但找不到,但是如果已经发布了一个问题,请告诉我!

How to create a Python keylogger

#in pynput, import keyboard Listener method
from pynput.keyboard import Listener

#set log file location
logFile = "/home/diego/log.txt"

def writeLog(key):
    '''
    This function will be responsible for receiving the key pressed.
     via Listener and write to log file
    '''

    #convert the keystroke to string
    keydata = str(key)

    #open log file in append mode
    with open(logFile, "a") as f:
        f.write(keydata)

#open the Keyboard Listener and listen for the on_press event
#when the on_press event occurs call the writeLog function

with Listener(on_press=writeLog) as l:
    l.join()

1 个答案:

答案 0 :(得分:1)

您可以从Key导入pynput.keyboard模块并检查击键的类型。

#in pynput, import keyboard Listener method
from pynput.keyboard import Listener, Key

#set log file location
logFile = "/home/diego/log.txt"

def writeLog(key):
    '''
    This function will be responsible for receiving the key pressed.
     via Listener and write to log file
    '''

    if(key == Key.left or key == Key.up):
        #convert the keystroke to string
        keydata = str(key)

        #open log file in append mode
        with open(logFile, "a") as f:
            f.write(keydata)

#open the Keyboard Listener and listen for the on_press event
#when the on_press event occurs call the writeLog function

with Listener(on_press=writeLog) as l:
    l.join()