有效阻止进程子进程生成和撤销权限的策略(Python)

编程


有没有有效的方法来防止进程生成子进程并撤销其权限? 我正在寻求一种强大的方法来完全阻止进程生成子进程的能力,并且如果可能的话,限制其权限并终止它及其子进程。 您有什么建议或策略可以有效实现此目的吗?

我尝试过的:

import psutil
import sys
import ctypes
import time<

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except Exception as e:
        print(f'Error checking admin privileges: {e}')
        return False

def run_as_admin():
    try:
        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
    except Exception as e:
        print(f'Error restarting as administrator: {e}')
        sys.exit(1)

def block_child_creation(process_name):
    try:
        for process in psutil.process_iter(['pid', 'name']):
            if process.info['name'].lower() == process_name.lower():
                # Suspend the process
                process.suspend()
                print(f'The process with PID {process.pid} has been suspended.')

                # Terminate the process and its children
                for child in process.children(recursive=True):
                    child.kill()
                psutil.wait_procs(process.children(), timeout=5)
                process.kill()
                process.wait(5)
                print(f'The process with PID {process.pid} and its children have been terminated.')

                break  # No need to continue searching after blocking the process

        # Verificar novamente se o processo foi encerrado
        for process in psutil.process_iter(['pid', 'name']):
            if process.info['name'].lower() == process_name.lower():
                print(f'The process {process_name} is still running.')
            else:
                print(f'No process with the name {process_name}.')
                break
    except psutil.NoSuchProcess:
        print(f'No process with the name {process_name} found.')
    except Exception as e:
        print(f'An unexpected error occurred: {e}')

def main():
    try:
        if not is_admin():
            print("Restarting as administrator!")
            run_as_admin()

        global nome_processo
        nome_processo = input("Enter the name of the process you want to block and terminate with child creation: ")

        block_child_creation(nome_processo)

    except KeyboardInterrupt:
        print("\nTermination process interrupted by the user.")
    except Exception as e:
        print(f'An unexpected error occurred: {e}')

if __name__ == "__main__":
    main()

解决方案1

想法不回答

尝试阻止进程创建,您可以尝试重复终止其所有子进程。
注意:添加延迟,以便用户计算机不会出现 BSOD(蓝屏死机)。

如果这不起作用或者您仍然想要留下一些进程/子进程,请尝试:
试图找出一些东西,请等待这个答案完成,或者也许是一些东西……

コメント

タイトルとURLをコピーしました