使用 win32api (Python) 获取进程的所有线程
Get all threads of a process using win32api (Python)
假设我有以下获取进程句柄的代码:
pid = 1234
procHandle = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED,pywintypes.FALSE,pid)
我将如何列出和获取其线程的句柄?
据我所知不存在 public api 枚举进程中的线程。但存在 NtQuerySystemInformation
和 SystemProcessInformation
或 SystemExtendedProcessInformation
- 它 return 系统中所有进程和线程的列表。通过使用这个你可以通过 id 找到进程中的所有线程,不需要打开进程
NTSTATUS DumpProcessThreads(_Out_ ULONG_PTR dwProcessId)
{
NTSTATUS status;
ULONG cb = 0x10000;
do
{
status = STATUS_NO_MEMORY;
if (PVOID buf = LocalAlloc(0, cb + 0x1000))
{
if (0 <= (status = NtQuerySystemInformation(SystemExtendedProcessInformation, buf, cb, &cb)))
{
status = STATUS_INVALID_CID;
union {
PVOID pv;
PBYTE pb;
PSYSTEM_PROCESS_INFORMATION pspi;
};
pv = buf;
ULONG NextEntryOffset = 0;
do
{
pb += NextEntryOffset;
if (pspi->UniqueProcessId == (HANDLE)dwProcessId)
{
status = STATUS_SUCCESS;
if (ULONG NumberOfThreads = pspi->NumberOfThreads)
{
PSYSTEM_EXTENDED_THREAD_INFORMATION TH = pspi->TH;
do
{
DbgPrint("%p: %p(%p) [%p]\n",
TH->ClientId.UniqueThread,
TH->StartAddress,
TH->Win32StartAddress,
TH->TebAddress);
} while (TH++, --NumberOfThreads);
}
break;
}
} while (NextEntryOffset = pspi->NextEntryOffset);
}
LocalFree(buf);
}
} while (status == STATUS_INFO_LENGTH_MISMATCH);
return status;
}
假设我有以下获取进程句柄的代码:
pid = 1234
procHandle = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED,pywintypes.FALSE,pid)
我将如何列出和获取其线程的句柄?
据我所知不存在 public api 枚举进程中的线程。但存在 NtQuerySystemInformation
和 SystemProcessInformation
或 SystemExtendedProcessInformation
- 它 return 系统中所有进程和线程的列表。通过使用这个你可以通过 id 找到进程中的所有线程,不需要打开进程
NTSTATUS DumpProcessThreads(_Out_ ULONG_PTR dwProcessId)
{
NTSTATUS status;
ULONG cb = 0x10000;
do
{
status = STATUS_NO_MEMORY;
if (PVOID buf = LocalAlloc(0, cb + 0x1000))
{
if (0 <= (status = NtQuerySystemInformation(SystemExtendedProcessInformation, buf, cb, &cb)))
{
status = STATUS_INVALID_CID;
union {
PVOID pv;
PBYTE pb;
PSYSTEM_PROCESS_INFORMATION pspi;
};
pv = buf;
ULONG NextEntryOffset = 0;
do
{
pb += NextEntryOffset;
if (pspi->UniqueProcessId == (HANDLE)dwProcessId)
{
status = STATUS_SUCCESS;
if (ULONG NumberOfThreads = pspi->NumberOfThreads)
{
PSYSTEM_EXTENDED_THREAD_INFORMATION TH = pspi->TH;
do
{
DbgPrint("%p: %p(%p) [%p]\n",
TH->ClientId.UniqueThread,
TH->StartAddress,
TH->Win32StartAddress,
TH->TebAddress);
} while (TH++, --NumberOfThreads);
}
break;
}
} while (NextEntryOffset = pspi->NextEntryOffset);
}
LocalFree(buf);
}
} while (status == STATUS_INFO_LENGTH_MISMATCH);
return status;
}