Python检查Windows指定进程是否存在

April 06, 2015

使用ctypes调用WinAPI,不依赖任何第三方库

# coding: utf-8  
from ctypes import *

psapi = windll.psapi
kernel = windll.kernel32


def checkProcesses(banProc):
    arr = c_ulong * 256
    lpidProcess = arr()
    cb = sizeof(lpidProcess)
    cbNeeded = c_ulong()
    hModule = c_ulong()
    count = c_ulong()
    modname = c_buffer(30)
    PROCESS_QUERY_INFORMATION = 0x0400
    PROCESS_VM_READ = 0x0010

    psapi.EnumProcesses(byref(lpidProcess),
                        cb,
                        byref(cbNeeded))

    # Number of processes returned
    nReturned = cbNeeded.value / sizeof(c_ulong())

    pidProcess = [i for i in lpidProcess][:nReturned]
    isBan = False
    for pid in pidProcess:

        # Get handle to the process based on PID
        hProcess = kernel.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                      False, pid)
        if hProcess:
            psapi.EnumProcessModules(
                hProcess, byref(hModule), sizeof(hModule), byref(count))
            psapi.GetModuleBaseNameA(
                hProcess, hModule.value, modname, sizeof(modname))
            proc = "".join([i for i in modname if i != '\x00'])
            if proc in banProc:
                isBan = True
            for i in range(modname._length_):
                modname[i] = '\x00'

            kernel.CloseHandle(hProcess)
    return isBan


if __name__ == '__main__':
    import time
    while True:
        time.sleep(1)
        print checkProcesses(['hh.exe'])

· EOF ·