简体   繁体   English

使用 win32api (Python) 获取进程的所有线程

[英]Get all threads of a process using win32api (Python)

Let's say I have the following code that gets a handle to a process:假设我有以下代码可以获取进程的句柄:

pid = 1234
procHandle = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED,pywintypes.FALSE,pid)

How would I list and get handles on it's threads?我将如何列出并获取其线程的句柄?

as far i know not exist public api which enumerated threads in process.据我所知,不存在枚举进程中的线程的公共 api。 but exist NtQuerySystemInformation and SystemProcessInformation or SystemExtendedProcessInformation - it return list of all processes and threads in system.但存在NtQuerySystemInformationSystemProcessInformationSystemExtendedProcessInformation - 它返回系统中所有进程和线程的列表。 by using this you can found all threads in process by id, not need open process通过使用它,您可以通过 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM