Listening to specific keys with pynput.Listener and keylogger?

﹥>﹥吖頭↗ 提交于 2020-03-25 19:01:29

问题


I have the following python script below:

But I want to "listen" or, if it's enough, just "record" to my log.txt, the following keys: Key.left and Key.up. How can I cause this restriction?

This question is similar but the code structures of her responses are somewhat different and would require a major change to allow the keylogger and this restriction on the Listener.

And this other question seems to me to be a potential source of inspiration for finding a method of solution.

I spent some time looking for a question that would give me this answer or help me to reflect on it but I couldn't find it but if there is a question already published please let me know!

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:


You can import Key module from pynput.keyboard and check for the type of key-strokes.

#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()


来源:https://stackoverflow.com/questions/59566884/listening-to-specific-keys-with-pynput-listener-and-keylogger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!