I was following this Stackoverflow question here. I'm trying to read the data stored in notepad.exe memory space. But my get_data function seems to return nothing. I have some text stored in notepad, i would like to retrieve that text from RAM and store it in a variable in Python. This is the code:
import os
from ctypes import *
from ctypes.wintypes import *
def get_pid(exe_name):
x = os.popen('tasklist /FI "ImageName eq '+process_name+'"').read()
if not x.find("No tasks are running") >= 0:
return int(list(filter(None, x[x.find(process_name):-1].split(" ")))[1])
return -1
def get_data(PROCESS_ID, PROCESS_HEADER_ADDR, 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)):
return (s.value,buf.raw)
process_name = "notepad.exe"
pid = get_pid(process_name)
process_header_addr = 0x7FF79A1E0000 # address from VMMap
data = get_data(pid, process_header_addr)
when i run this code, there is no data it just prints nothing:
>>> print(data)
None
>>>
how can I retrieve the data?
[MS.Docs]: ReadProcessMemory function states:
Here's a small example.
code00.py:
Output:
Update #0
I don't know how Notepad organizes its memory internally. I can assume that the text is stored in a buffer (or maybe more, could be one per line, ...) which should reside in the heap area. But where exactly I can't say. You could inspect the process memory using a tool (I know that CheatEngine can do that) do a match between the memory contents and the text, and get that address, and paste it in the code, but I think that would:
All in all, I don't think this is the way to go. You could search for alternatives, like using WinAPIs to send messages (maybe WM_GETTEXT) to the Notepad window to get the text. I don't know exactly how to do it, but I remember I was able to programmatically insert characters in Notepad using WM_CHAR.
Or you could send a Ctrl + A, Ctrl + C, and then get the clipboard contents.