gpt4 book ai didi

python - 如何按名称查找进程并使用 ctypes 终止进程?

转载 作者:可可西里 更新时间:2023-11-01 13:50:38 25 4
gpt4 key购买 nike

在 Windows 上,我想找到名为“exename.exe”的进程,然后将其终止。

我如何通过 ctypes 而不是任何其他第 3 方模块来做到这一点?

最佳答案

试试这个:

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)

关于python - 如何按名称查找进程并使用 ctypes 终止进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6980246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com