Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

python - Finding the baseaddress of a running process

Ive got the following code:

import subprocess
from ctypes import *

#-Part where I get the PID and declare all variables-#

OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory

processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, PID)

ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead))

All this is working flawless, but since some processes uses a so called BaseAddress or StartAddress. And in my case the size of this BaseAddress is random from time to time. As suggested here I tried using the following code:

BaseAddress = win32api.GetModuleHandle(None)

All it does is giving the same hex value over and over again, even though I for sure know that my BaseAddress have changed.

Screenshot from the linked thread showing what Im looking for (where the left part is the baseaddress): CE BaseAddress

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I did manage to find a solution for python 3.5 32-bit and 64 bit.

For 32 bit I used psutil and pymem (as already suggested on this question).:

import psutil
import pymem

my_pid = None
pids = psutil.pids()
for pid in pids:
    ps = psutil.Process(pid)
    # find process by .exe name, but note that there might be more instances of solitaire.exe
    if "solitaire.exe" in ps.name():
        my_pid = ps.pid
        print( "%s running with pid: %d" % (ps.name(), ps.pid) )

base_address = pymem.process.base_address(pid)

For 64 bit pymem was not working. I found suggestions using win32api.GetModuleHandle(fileName) but it required win32api.LoadLibrary(fileName) which was not using an already running process.

Therefore I found this suboptimal solution, since this returns a whole list of possibilities:

import win32process
import win32api

# first get pid, see the 32-bit solution

PROCESS_ALL_ACCESS = 0x1F0FFF
processHandle = win32api.OpenProcess(PROCESS_ALL_ACCESS, False, my_pid)
modules = win32process.EnumProcessModules(processHandle)
processHandle.close()
base_addr = modules[0] # for me it worked to select the first item in list...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...