前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何利用Python杀进程并保持驻留后台检测

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

作者头像
繁华是客
发布2023-03-03 20:16:33
3410
发布2023-03-03 20:16:33
举报

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

安装Python和使用PyChram编译器

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

安装psutil库

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

命令安装

代码语言:javascript
复制
pip install psutil

杀死进程

代码语言:javascript
复制
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)

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

最简洁的命令其实是

代码语言:javascript
复制
import os

os.system('taskkill /IM OUTLOOK.EXE /F')

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

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

代码语言:javascript
复制
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)

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

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

代码语言:javascript
复制
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

ChatGPT生成

以下代码使用ChatGPT生成。

添加直接以管理员启动

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

代码语言:javascript
复制
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)

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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()

管理员杀Adobe系列软件 含UI

代码语言:javascript
复制
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()

py文件改为exe

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

代码语言:javascript
复制
pip install auto-py-to-exe

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

代码语言:javascript
复制
pyinstaller --noconfirm --onefile --windowed
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-10-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装Python和使用PyChram编译器
  • 安装psutil库
  • 杀死进程
  • 杀死进程高阶版 - 杀死多进程
  • 杀死进程60秒后自动结束版
  • ChatGPT生成
    • 添加直接以管理员启动
      • 无管理员杀Adobe系列软件 含UI
        • 管理员杀Adobe系列软件 含UI
        • py文件改为exe
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档