在Windows上使用python进行键盘记录

时间:2017-11-27 21:26:05

标签: python windows

我的尝试如下,当我打字时它抓得很好,但如果按下多个键则会很糟糕。它只捕获第一个按下的键。

我删除了所有与键盘记录无关的内容。

import win32console
import win32gui
import pythoncom, pyHook
import threading
import pickle

class keylogger(object):

    def init(self, ifPrintDetail = False):
        self.keylog_enable = False
        self.ifPrintDetail = ifPrintDetail
        self.log = ''    

    def KeyEvent(self, event):
        if self.keylog_enable:        
            self.log += event.Key
            if self.ifPrintDetail:
                print ('MessageName:',event.MessageName )
                print ('Message:',event.Message)
                print ('Time:',event.Time)
                print ('Window:',event.Window)
                print ('WindowName:',event.WindowName)
                print ('Ascii:', event.Ascii, chr(event.Ascii) )
                print ('Key:', event.Key)
                print ('KeyID:', event.KeyID)
                print ('ScanCode:', event.ScanCode)
                print ('Extended:', event.Extended)
                print ('Injected:', event.Injected)
                print ('Alt', event.Alt)
                print ('Transition', event.Transition)
                print ('---')
            elif event.MessageName == 'key down':
                print(event.Key, end='')

    def threadkeylog(self):
        win = win32console.GetConsoleWindow()
        win32gui.ShowWindow(win, 0)
        # create a hook manager object for both key up and down
        self.hm=pyHook.HookManager()
        #i want both up and down key event
        self.hm.KeyDown = self.KeyEvent
        self.hm.KeyUp = self.KeyEvent
        # set the hook
        self.hm.HookKeyboard()
        #start sending messages, this seems not to stop except WM_QUIT
        pythoncom.PumpMessages()

    def go(self):
        #build and start a thread
        self.keylog_enable = True
        self.threadkl = threading.Thread(target = self.threadkeylog)
        self.threadkl.start()

    def pause(self):
        self.keylog_enable = False

    def save(self):
        pickle.dump(self.log, open('keylog.txt', 'wb'))

您可以将其与

一起使用
kl = keylogger()
kl.init()
kl.go()#build and run a thread
kl.pause()#"pause" the thread
kl.save()#will save what you have typed to a file in working directory
print(pickle.load(open('keylog.txt', "rb")))#take a look at it

我这样做是为了收集我自己玩赛车游戏的关键日志,用于训练我机器学习项目的数据。所以,比方说,如果我用简单的" WASD"来控制我的赛车。按钮,我可能会举行" W"和" A"向左转并加速。因此,我希望同时捕获它们,但这些键冲突,并且它只捕获一个字符。

0 个答案:

没有答案