Python查杀Windows系统中指定进程
下面的代码需要Windows API和Python标准库ctypes的相关知识。
from ctypes.wintypes import *
from ctypes import *
kernel32 = windll.kernel32
class tagPROCESSENTRY32(Structure): #定义结构体
_fields_ = [('dwSize', DWORD),
('cntUsage', DWORD),
('th32ProcessID', DWORD),
('th32DefaultHeapID', POINTER(ULONG)),
('th32ModuleID', DWORD),
('cntThreads', DWORD),
('th32ParentProcessID', DWORD),
('pcPriClassBase', LONG),
('dwFlags', DWORD),
('szExeFile', c_char * 260)]
def killProcess(processNames):
#创建进程快照
hSnapshot = kernel32.CreateToolhelp32Snapshot(15, 0)
fProcessEntry32 = tagPROCESSENTRY32()
if hSnapshot:
fProcessEntry32.dwSize = sizeof(fProcessEntry32)
hasmore = kernel32.Process32First(hSnapshot, byref(fProcessEntry32))
#枚举进程
while hasmore:
#可执行文件
processName = (fProcessEntry32.szExeFile)
#进程ID
processID = fProcessEntry32.th32ProcessID
if processName.decode().lower() in processNames:
#获取进程句柄
hProcess = kernel32.OpenProcess(1, False, processID)
#结束进程
kernel32.TerminateProcess(hProcess,0)
#获取下一个进程
hasmore = kernel32.Process32Next(hSnapshot, byref(fProcessEntry32))
#待查杀的进程列表
processNames = ('notepad.exe', 'mspaint.exe')
killProcess(processNames)