本文介绍了如何通过名称查找进程并使用ctypes杀死进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows上,我想找到名称为'exename.exe'的进程,然后将其杀死。

On Windows, I want to find a process by the name of 'exename.exe', and then kill it.

如何通过ctypes not其他任何第三方模块?

How can I do it by ctypes not any other 3rd-party module?

推荐答案

请尝试以下操作:

import sys, os.path, ctypes, ctypes.wintypes

Psapi = ctypes.WinDLL('Psapi.dll')
EnumProcesses = Psapi.EnumProcesses
EnumProcesses.restype = ctypes.wintypes.BOOL
GetProcessImageFileName = Psapi.GetProcessImageFileNameA
GetProcessImageFileName.restype = ctypes.wintypes.DWORD

Kernel32 = ctypes.WinDLL('kernel32.dll')
OpenProcess = Kernel32.OpenProcess
OpenProcess.restype = ctypes.wintypes.HANDLE
TerminateProcess = Kernel32.TerminateProcess
TerminateProcess.restype = ctypes.wintypes.BOOL
CloseHandle = Kernel32.CloseHandle

MAX_PATH = 260
PROCESS_TERMINATE = 0x0001
PROCESS_QUERY_INFORMATION = 0x0400

count = 32
while True:
    ProcessIds = (ctypes.wintypes.DWORD*count)()
    cb = ctypes.sizeof(ProcessIds)
    BytesReturned = ctypes.wintypes.DWORD()
    if EnumProcesses(ctypes.byref(ProcessIds), cb, ctypes.byref(BytesReturned)):
        if BytesReturned.value<cb:
            break
        else:
            count *= 2
    else:
        sys.exit("Call to EnumProcesses failed")

for index in range(BytesReturned.value / ctypes.sizeof(ctypes.wintypes.DWORD)):
    ProcessId = ProcessIds[index]
    hProcess = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, False, ProcessId)
    if hProcess:
        ImageFileName = (ctypes.c_char*MAX_PATH)()
        if GetProcessImageFileName(hProcess, ImageFileName, MAX_PATH)>0:
            filename = os.path.basename(ImageFileName.value)
            if filename == 'notepad.exe':
                TerminateProcess(hProcess, 1)
        CloseHandle(hProcess)

这篇关于如何通过名称查找进程并使用ctypes杀死进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:21