如何利用Python杀进程并保持驻留后台检测

简介: 本教程介绍如何使用Python编写进程监控与杀进程脚本,结合psutil库实现后台驻留、定时检测并强制终止指定进程。内容涵盖基础杀进程、多进程处理、自动退出机制、管理员权限启动及图形界面设计,并提供将脚本打包为exe的方法,适用于需持续清理顽固进程的场景。

如何利用Python杀进程并保持后台检测驻留?
因为有一些软件一直驻留,想删的话之后又重新出现了,所以想到利用Python来进行杀进程。

安装Python和使用PyChram编译器

Python的安装在这里并不想多少,目前网络上的教程都是正确的。
自从用了PyChram的编译器,世界更加美好了。编译环境可以根据每个项目不一样而不同。
下载地址:https://www.jetbrains.com/pycharm/

安装psutil库

psutil默认是没有这个库的,文档可以参考psutil wiki

命令安装

pip install psutil
AI 代码解读

杀死进程

import psutil
from time import sleep
active = 1 #并无意义的flag 正好可以做一个while无限循环
process_to_kill = 'QQBrowser.exe'
while active == 1 :
    for proc in psutil.process_iter():
        #进程名字清单
        try:
            if proc.name().lower() == process_to_kill.lower(): #进程名字对比(变成小写对比)
                print(proc.pid) #proc.pid就是该进程PID
                p = psutil.Process(proc.pid)
                #定义P为这些进程PID
                p.terminate()
                #通过这个内置功能杀进程的方式直接删除这些进程
                #你也可以通过os.system('taskkill /IM QQBrowser.exe /F')
                #的方式删除,需要import os
                print('Successfully kill', process_to_kill, 'apps.')
        except psutil.NoSuchProcess:
            pass
    sleep(15)
AI 代码解读

使用while是因为不用的话,进程会自己结束,然后就没有然后了。
所以使用了无限循环来驻留这个程序。

最简洁的命令其实是

import os

os.system('taskkill /IM OUTLOOK.EXE /F')
AI 代码解读

杀死进程高阶版 - 杀死多进程

实际上,使用pid和terminate并不是特别高效
我们还可以使用kill来实现

import psutil
from time import sleep
active = 1 #并无意义的flag 正好可以做一个while无限循环
process_to_kill = {
   'QQBrowser.exe', 'QQMusic.exe', 'QQImage.exe'}
#List里面无法直接变成小写,具体可以Google
while active == 1 :
    for proc in psutil.process_iter():
        #进程名字清单
        try:
            if proc.name() in process_to_kill:
                proc.kill()
                print('Successfully kill those apps.')
        except psutil.NoSuchProcess:
            pass
    sleep(15)
AI 代码解读

杀死进程60秒后自动结束版

如果是无限循环的话,让进程一直存在似乎不太好,于是就想到自动结束进程的方法。
来源:stackoverflow

import os
import time
import psutil
from datetime import datetime
from threading import Timer



def exitfunc():
    print("Exit Time", datetime.now())
    os._exit(0)

Timer(60, exitfunc).start() # exit in 60 seconds

while True: # infinite loop, replace it with your code that you want to interrupt
    print("Current Time", datetime.now())
    time.sleep(1)
    process_to_kill = {
   'AdobeARM.exe', 'acrotray.exe','QQProtect.exe','pcas.exe','wwbizsrv.exe','dy_service.exe'}
    #List里面无法直接变成小写,具体可以Google
    for proc in psutil.process_iter():
          #进程名字清单
        try:
            if proc.name() in process_to_kill:
                proc.kill()
                print('Successfully kill those apps.')
        except psutil.NoSuchProcess:
            pass
AI 代码解读

ChatGPT生成

以下代码使用ChatGPT生成。

添加直接以管理员启动

一般的添加管理员启动只需要添加

import ctypes
import sys

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    # code to be executed as an administrator
else:
    # re-run the script with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
AI 代码解读

我们将我们代码和以管理员启动代码结合,结果如下:

import os
import time
import psutil
from datetime import datetime
from threading import Timer
import ctypes
import sys

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def exitfunc():
    print("Exit Time", datetime.now())
    os._exit(0)

if not is_admin():
    # re-run the script with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
    exit()

Timer(60, exitfunc).start()  # exit in 60 seconds

while True:  # infinite loop, replace it with your code that you want to interrupt
    print("Current Time", datetime.now())
    time.sleep(1)
    process_to_kill = {'AdobeARM.exe', 'acrotray.exe', 'CoreSync', 'CCLibrary.exe', 'AdobeIPCBroker.exe'
        , 'Adobe Desktop Service.exe','AdobeNotificationClient.exe','CCXProcess.exe','Creative Cloud Helper.exe'
        ,'Creative Cloud UI Helper.exe','Creative Cloud.exe','AdobeUpdateService.exe'}

    # List里面无法直接变成小写,具体可以Google
    for proc in psutil.process_iter():
        # 进程名字清单
        try:
            if proc.name() in process_to_kill:
                proc.kill()
                print('Successfully kill those apps.')
        except psutil.NoSuchProcess:
            pass
AI 代码解读

无管理员杀Adobe系列软件 含UI

import tkinter as tk
from time import sleep
from threading import Thread
import psutil

class ProcessKiller:
    def __init__(self):
        self.active = False
        self.processes_to_kill = {'AdobeARM.exe', 'acrotray.exe', 'CoreSync', 'CCLibrary.exe', 'AdobeIPCBroker.exe'
        , 'Adobe Desktop Service.exe','AdobeNotificationClient.exe','CCXProcess.exe','Creative Cloud Helper.exe'
        ,'Creative Cloud UI Helper.exe','Creative Cloud.exe','AdobeUpdateService.exe'}
        self.thread = None

    def start(self):
        if self.thread is not None and self.thread.is_alive():
            print('Thread already running')
            return

        self.active = True
        self.thread = Thread(target=self.kill_processes)
        self.thread.start()
        print('Thread started')

    def stop(self):
        self.active = False
        if self.thread is not None:
            self.thread.join()
            print('Thread stopped')
        else:
            print('Thread not running')

    def kill_processes(self):
        while self.active:
            for proc in psutil.process_iter():
                try:
                    if proc.name() in self.processes_to_kill:
                        proc.kill()
                        print('Successfully killed process', proc.name())
                except psutil.NoSuchProcess:
                    pass
            sleep(15)

# Create a Tkinter window with start and stop buttons
root = tk.Tk()

killer = ProcessKiller()

start_button = tk.Button(root, text="Start", command=killer.start)
start_button.pack()

stop_button = tk.Button(root, text="Stop", command=killer.stop)
stop_button.pack()

root.mainloop()
AI 代码解读

管理员杀Adobe系列软件 含UI

import os
import sys
import ctypes
from time import sleep
from threading import Thread
import psutil
import tkinter as tk
from datetime import datetime

class ProcessKiller:
    def __init__(self):
        self.active = False
        self.processes_to_kill = {'AdobeARM.exe', 'acrotray.exe', 'CoreSync', 'CCLibrary.exe', 'AdobeIPCBroker.exe'
        , 'Adobe Desktop Service.exe','AdobeNotificationClient.exe','CCXProcess.exe','Creative Cloud Helper.exe'
        ,'Creative Cloud UI Helper.exe','Creative Cloud.exe','AdobeUpdateService.exe'}
        self.thread = None

    def start(self):
        if self.thread is not None and self.thread.is_alive():
            self.log("Thread already running")
            return

        self.active = True
        self.thread = Thread(target=self.kill_processes)
        self.thread.start()
        self.log("Thread started")

    def stop(self):
        self.active = False
        if self.thread is not None:
            self.thread.join()
            self.log("Thread stopped")
        else:
            self.log("Thread not running")

    def kill_processes(self):
        while self.active:
            for proc in psutil.process_iter():
                try:
                    if proc.name() in self.processes_to_kill:
                        proc.kill()
                        self.log(f"Successfully killed process {proc.name()}")
                except psutil.NoSuchProcess:
                    pass
            sleep(15)


    def log(self, message):
        now = datetime.now()
        timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
        message = f"[{timestamp}] {message}"
        print(message)
        if self.log_var is not None:
            # Split the current log text into separate lines
            log_text = self.log_var.get().split('\n')
            # Keep only the last 5 lines of the log
            log_text = log_text[-5:]
            # Add the new message to the end of the log
            log_text.append(message)
            # Update the log area with the updated log text
            self.log_var.set('\n'.join(log_text))
            # Write the log message to a text file
            with open("process_killer_log.txt", "a") as f:
                f.write(message + "\n")

class App:
    def __init__(self, master):
        self.master = master
        master.title("Process Killer")

        # Create log area
        self.log_var = tk.StringVar()
        self.log_var.set("Process Killer started\n")
        self.log_label = tk.Label(master, textvariable=self.log_var, justify="left")
        self.log_label.grid(row=0, column=0, padx=10, pady=10, sticky="w")

        # Create start button
        self.start_button = tk.Button(master, text="Start", command=self.start_process_killer)
        self.start_button.grid(row=1, column=0, padx=10, pady=10, sticky="w")

        # Create stop button
        self.stop_button = tk.Button(master, text="Stop", command=self.stop_process_killer, state="disabled")
        self.stop_button.grid(row=2, column=0, padx=10, pady=10, sticky="w")

    def start_process_killer(self):
        self.process_killer = ProcessKiller()
        self.process_killer.log_var = self.log_var
        self.process_killer.start()
        self.start_button.config(state="disabled")
        self.stop_button.config(state="normal")

    def stop_process_killer(self):
        self.process_killer.stop()
        self.start_button.config(state="normal")
        self.stop_button.config(state="disabled")

# Check if script is running with admin rights
if not ctypes.windll.shell32.IsUserAnAdmin():
    print("Script not running with admin rights, relaunching...")
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
    sys.exit()

# Create a Tkinter window and start the UI
root = tk.Tk()
app = App(root)
root.mainloop()
AI 代码解读

py文件改为exe

https://pypi.org/project/auto-py-to-exe/

pip install auto-py-to-exe
AI 代码解读

安装好之后,直接在Terminal运行auto-py-to-exe即可。
里面可以选择单独一个exe文件或者文件夹的形式,也可以隐藏Console,只是以UI的形式出现。
实际上,就是pyinstaller的命令。

pyinstaller --noconfirm --onefile --windowed
AI 代码解读
目录
打赏
0
6
6
0
69
分享
相关文章
|
5月前
|
时间序列异常检测:MSET-SPRT组合方法的原理和Python代码实现
MSET-SPRT是一种结合多元状态估计技术(MSET)与序贯概率比检验(SPRT)的混合框架,专为高维度、强关联数据流的异常检测设计。MSET通过历史数据建模估计系统预期状态,SPRT基于统计推断判定偏差显著性,二者协同实现精准高效的异常识别。本文以Python为例,展示其在模拟数据中的应用,证明其在工业监控、设备健康管理及网络安全等领域的可靠性与有效性。
729 13
时间序列异常检测:MSET-SPRT组合方法的原理和Python代码实现
|
5月前
|
Linux 进程前台后台切换与作业控制
进程前台/后台切换及作业控制简介: 在 Shell 中,启动的程序默认为前台进程,会占用终端直到执行完毕。例如,执行 `./shella.sh` 时,终端会被占用。为避免不便,可将命令放到后台运行,如 `./shella.sh &`,此时终端命令行立即返回,可继续输入其他命令。 常用作业控制命令: - `fg %1`:将后台作业切换到前台。 - `Ctrl + Z`:暂停前台作业并放到后台。 - `bg %1`:让暂停的后台作业继续执行。 - `kill %1`:终止后台作业。 优先级调整:
242 5
Python实用技巧:轻松驾驭多线程与多进程,加速任务执行
在Python编程中,多线程和多进程是提升程序效率的关键工具。多线程适用于I/O密集型任务,如文件读写、网络请求;多进程则适合CPU密集型任务,如科学计算、图像处理。本文详细介绍这两种并发编程方式的基本用法及应用场景,并通过实例代码展示如何使用threading、multiprocessing模块及线程池、进程池来优化程序性能。结合实际案例,帮助读者掌握并发编程技巧,提高程序执行速度和资源利用率。
208 0
Python图像处理中的内存泄漏问题:原因、检测与解决方案
在Python图像处理中,内存泄漏是常见问题,尤其在处理大图像时。本文探讨了内存泄漏的原因(如大图像数据、循环引用、外部库使用等),并介绍了检测工具(如memory_profiler、objgraph、tracemalloc)和解决方法(如显式释放资源、避免循环引用、选择良好内存管理的库)。通过具体代码示例,帮助开发者有效应对内存泄漏挑战。
236 1
Python中的Paramiko与FTP文件夹及文件检测技巧
通过使用 Paramiko 和 FTP 库,开发者可以方便地检测远程服务器上的文件和文件夹是否存在。Paramiko 提供了通过 SSH 协议进行远程文件管理的能力,而 `ftplib` 则提供了通过 FTP 协议进行文件传输和管理的功能。通过理解和应用这些工具,您可以更加高效地管理和监控远程服务器上的文件系统。
175 20
使用 OpenCV 和 Python 轻松实现人脸检测
本文介绍如何使用OpenCV和Python实现人脸检测。首先,确保安装了OpenCV库并加载预训练的Haar特征模型。接着,通过读取图像或视频帧,将其转换为灰度图并使用`detectMultiScale`方法进行人脸检测。检测到的人脸用矩形框标出并显示。优化方法包括调整参数、多尺度检测及使用更先进模型。人脸检测是计算机视觉的基础技术,具有广泛应用前景。
245 10
python中的线程和进程(一文带你了解)
欢迎来到瑞雨溪的博客,这里是一位热爱JavaScript和Vue的大一学生分享技术心得的地方。如果你从我的文章中有所收获,欢迎关注我,我将持续更新更多优质内容,你的支持是我前进的动力!🎉🎉🎉
104 0
Python中的并发编程:探索多线程与多进程的奥秘####
本文深入探讨了Python中并发编程的两种主要方式——多线程与多进程,通过对比分析它们的工作原理、适用场景及性能差异,揭示了在不同应用需求下如何合理选择并发模型。文章首先简述了并发编程的基本概念,随后详细阐述了Python中多线程与多进程的实现机制,包括GIL(全局解释器锁)对多线程的影响以及多进程的独立内存空间特性。最后,通过实例演示了如何在Python项目中有效利用多线程和多进程提升程序性能。 ####
使用Python实现智能食品质量检测的深度学习模型
使用Python实现智能食品质量检测的深度学习模型
422 1
python多进程一文够了!!!
本文介绍了高效编程中的多任务原理及其在Python中的实现。主要内容包括多任务的概念、单核和多核CPU的多任务实现、并发与并行的区别、多任务的实现方式(多进程、多线程、协程等)。详细讲解了进程的概念、使用方法、全局变量在多个子进程中的共享问题、启动大量子进程的方法、进程间通信(队列、字典、列表共享)、生产者消费者模型的实现,以及一个实际案例——抓取斗图网站的图片。通过这些内容,读者可以深入理解多任务编程的原理和实践技巧。
485 1

热门文章

最新文章

推荐镜像

更多
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问