I didn't install psutil
, but just pulled a process ID and valid virtual address using Task Manager and SysInternals VMMap. The numbers will vary of course.
Good practice with ctypes is to define the argument types and return value via .argtypes
and .restype
. Get your own instance of the kernel32 library because changing the attributes of the cached windll.kernel32
instance could cause issues with other modules using ctypes and kernel32.
You need a valid virtual address. In answer to your 2nd problem, I think VMMap proves there is a way to do it. Pick up a copy of Windows Internals to learn the techniques.
from ctypes import *
from ctypes.wintypes import *
PROCESS_ID = 9476 # From TaskManager for Notepad.exe
PROCESS_HEADER_ADDR = 0x7ff7b81e0000 # From SysInternals VMMap utility
# read from addresses
STRLEN = 255
PROCESS_VM_READ = 0x0010
k32 = WinDLL('kernel32')
k32.OpenProcess.argtypes = DWORD,BOOL,DWORD
k32.OpenProcess.restype = HANDLE
k32.ReadProcessMemory.argtypes = HANDLE,LPVOID,LPVOID,c_size_t,POINTER(c_size_t)
k32.ReadProcessMemory.restype = BOOL
process = k32.OpenProcess(PROCESS_VM_READ, 0, PROCESS_ID)
buf = create_string_buffer(STRLEN)
s = c_size_t()
if k32.ReadProcessMemory(process, PROCESS_HEADER_ADDR, buf, STRLEN, byref(s)):
print(s.value,buf.raw)
Output (Note 'MZ' is the start of a program header):
255 b'MZx90x00x03x00x00x00x04x00x00x00xffxffx00x00xb8x00x00x00x00x00x00x00@x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00xe8x00x00x00x0ex1fxbax0ex00xb4xcd!xb8x01Lxcd!This program cannot be run in DOS mode.
$x00x00x00x00x00x00x00xd0x92xa7xd1x94xf3xc9x82x94xf3xc9x82x94xf3xc9x82x9dx8bZx82x8axf3xc9x82xfbx97xcax83x97xf3xc9x82xfbx97xcdx83x83xf3xc9x82xfbx97xccx83x91xf3xc9x82xfbx97xc8x83x8fxf3xc9x82x94xf3xc8x82x82xf2xc9x82xfbx97xc1x83x8dxf3xc9x82xfbx976x82x95xf3xc9x82xfbx97xcbx83x95xf3xc9x82Richx94xf3xc9x82x00x00x00x00x00x00x00x00PEx00x00dx86x06x00^'x0fx84x00x00x00x00x00x00x00x00xf0x00"'
Here's a screenshot of VMMap indicating the header address of notepad.exe:
Here's a screenshot of a hexdump of the content of notepad.exe that matches the output of the program:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…