进程管理工具-暴力

import logging
import os
import subprocess
import traceback

__author__ = 'James'
logger = logging.getLogger(__name__)


class ProcessMgmtHelper:
    """
    当前仅过滤python进程
    """
    def __init__(self):
        pass

    @staticmethod
    def get_process_invoke_command() -> list:
        """
        @return:
        """
        pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
        ps_result = []
        for pid in pids:
            try:
                with open(os.path.join('/proc', pid, 'cmdline'), 'rb') as f:
                    command = f.read().decode("utf-8").replace("\x00", " ")
                if command.find("python") != -1:
                    ps_result.append(pid + ' ' + command)
            except IOError:  # proc has already terminated
                continue
        return ps_result

    @staticmethod
    def process_already_running(cmdline, within_proc=False):
        """
        检测进程是否存在
        @param cmdline:
        @param within_proc:
        @return:
        """
        result = ProcessMgmtHelper.get_process_invoke_command()
        count = 0

        process_number = 1
        if within_proc:
            process_number = 2

        for line in result:
            if line.find(cmdline) != -1:
                print(line)
                count += 1

        if count >= process_number:
            return True
        else:
            return False

    @staticmethod
    def find_process_id(app_name):
        result = ProcessMgmtHelper.get_process_invoke_command()
        for line in result:
            if line.find(app_name) != -1:
                return int(line.split()[0])

    @staticmethod
    def write_pid(filename, pid):
        with open(filename, 'w') as fd:
            fd.write(str(pid))

    @staticmethod
    def read_pid(filename):
        try:
            with open(filename, 'r') as fd:
                pid = fd.read().strip()
        except:
            pid = -1
        return pid

    @staticmethod
    def kill_process_with_pid(pid):
        try:
            subprocess.check_call(['kill', str(pid)])
        except:
            logger.info(traceback.format_exc())

    @staticmethod
    def terminate_process_with_pid(pid):
        try:
            subprocess.check_call(['kill', '-INT', str(pid)])
        except:
            logger.info(traceback.format_exc())

    @staticmethod
    def kill_process_with_file(filename):
        pid = ProcessMgmtHelper.read_pid(filename)
        if pid != -1:
            try:
                subprocess.check_call(['kill', '-9', str(pid)])
            except:
                logger.info(traceback.format_exc())
        else:
            logger.info(filename + ' does not exist')

    @staticmethod
    def start_process(process_cmd, popen=False):
        try:
            if popen:
                print(subprocess.Popen(["nohup", "python3", process_cmd, "&"]))
            else:
                print(subprocess.check_call(["nohup", "python3", process_cmd, "&"]))
        except subprocess.CalledProcessError:
            logger.error(traceback.format_exc())


if __name__ == '__main__':
    print(ProcessMgmtHelper.get_process_invoke_command())

    print(ProcessMgmtHelper.process_already_running("/usr/bin/supervisord"))

    print(ProcessMgmtHelper.process_already_running("/usr/bin/supervisord", within_proc=True))

    print(ProcessMgmtHelper.start_process("process_test.py"))

posted @ 2023-02-20 18:06  公众号海哥python  阅读(20)  评论(0)    收藏  举报