我的程式在 Windows 10 上運行提升:
- 獲取正在運行的 notepad.exe 行程的 PID
- 通過接收到它的句柄
OpenProcess - 列舉名稱為 notepad.exe 的行程模塊的 baseAddress
- 來電
ReadProcessMemory
import ctypes
from ctypes import wintypes
import win32process
import psutil
targetProcess = "notepad.exe"
PROCESS_ALL_ACCESS = 0x1F0FFF
BUFFER_SIZE = 200
def getpid():
for proc in psutil.process_iter():
if proc.name() == targetProcess:
return proc.pid
def main():
status = ctypes.windll.ntdll.RtlAdjustPrivilege(20, 1, 0, ctypes.byref(ctypes.c_bool()))
if(status == -1073741727):
print("STATUS_PRIVILEGE_NOT_HELD - A required privilege is not held by the client.")
hProcess = ctypes.windll.kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, getpid()) # handle to process
lpBuffer = ctypes.create_string_buffer(BUFFER_SIZE) # Buffer we want to write results to
targetProcessBaseAddress = None # base address of the target processes entry module
modules = win32process.EnumProcessModules(hProcess) # Retreive modules of target process
for module in modules:
name = str(win32process.GetModuleFileNameEx(hProcess, module))
if targetProcess in name:
targetProcessBaseAddress = hex(module)
count = ctypes.c_ulong(0)
res = ctypes.windll.kernel32.ReadProcessMemory(hProcess, targetProcessBaseAddress, ctypes.byref(lpBuffer), BUFFER_SIZE, ctypes.byref(count))
if res == 0:
err = ctypes.windll.kernel32.GetLastError()
if (err == 299):
print("ERROR_PARTIAL_COPY - Only part of a ReadProcessMemory or WriteProcessMemory request was completed.")
else:
print(err)
else:
print(lpBuffer.raw)
if __name__ == '__main__':
main()
以上是通過python3.8使用本機ctypes庫完成的。
我希望看到一個 hexdump 或除0x00,0x00.. 之外的任何資料,但似乎我的錯誤出現在提供給 的引數中ReadProcessMemory,這是由于從 回傳的錯誤 299 所致GetLastError(),這表明:
“ERROR_PARTIAL_COPY - 僅完成了 ReadProcessMemory 或 WriteProcessMemory 請求的一部分。”
不知道我在哪里搞砸了,非常感謝您的建議和幫助!
uj5u.com熱心網友回復:
ReadProcessMemory第二個引數是一個LPCVOID(指向 const void* 的長指標),但您傳遞的結果hex回傳一個字串(然后將轉換為 ctypes 背景關系中指向字串的指標)。關注@CristiFati 評論并使用 ctypes argtypes 和 restype會立即發現問題。
不要直接
GetLastError從 win32 API 使用。解釋器在其生命周期內可以自由呼叫任何 Windows API,因此當您呼叫此 API 時,您不知道它是腳本的結果還是解釋器出于自身目的呼叫的 API。為此,ctypes 提出了一個特定的變數,它以ctypes.get_last_error.
最好的方法是用類似的東西開始你的腳本:
import ctypes
# obtain kernel32 WinDLL ensuring that we want to cache the last error for each API call.
kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
# start prototyping your APIs
OpenProcess = kernel32.OpenProcess
OpenProcess.argtypes = [ ... ]
OpenProcess.restype = ...
# then call the api
res = OpenProcess( ... )
#ensure you check the result by calling the cached last error
if not res:
err = ctypes.get_last_error()
# you might also raise
raise ctypes.WinError(err)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411746.html
標籤:
