Fork me on GitHub

python脚本监听nginx是否运行

import sys
import time
import os
import logging
from logging.handlers import RotatingFileHandler
import config

class Nginx_listen(object):
    logger = None
    @property
    def setup_log(self):
        return self.logger
    @setup_log.setter
    def setup_log(self,log_name):
        """创建日志配置"""
        logger = logging.getLogger(log_name)
        log_path = os.path.join(config.log_path,log_name)
        logger.setLevel(logging.INFO)
        file_handler = RotatingFileHandler(
            log_path, 'a', config.MAX_BYTE, config.BACKUP_COUNT
        )
        file_handler.setFormatter(
            logging.Formatter(
                "[%(asctime)s] [%(process)d] [%(levelname)s] - %(module)s.%(funcName)s (%(filename)s:%(lineno)d) - %(message)s"
            )
        )
        logger.addHandler(file_handler)
        self.logger = logger
    @staticmethod
    def write_pid(pid):
        """nginx的进程id写入文件"""
        with open(config.pid_path,'w') as fp:
            fp.write("%s\n"%pid)
    @staticmethod
    def read_pid():
        """读取保存文件内nginx的进程id"""
        with open(config.pid_path, 'r') as fp:
            pid = fp.read().strip()
        return pid
    def check_nginx_pid(self):
        """获取启动nginx 的进程id"""
        current_pid = os.popen("sudo pgrep -lo nginx |grep -v grep|awk '{print $1}'").read()
        if current_pid:
            self.write_pid(current_pid)
        return current_pid

    def check_nginx_run(self):
        """检查nginx是否启动"""
        status = False
        nginx_pid = self.check_nginx_pid()
        nginx_start_data = os.popen("sudo ps aux|grep nginx |grep -v grep|awk 'NR==1{print $9}'").read()
        nginx_path = os.popen("sudo ps aux|grep nginx |grep -v grep|awk 'NR==1{print $14}'").read()
        current_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        if nginx_pid and nginx_path:
            self.logger.info("current_time: %s;startime: %s;nginx_path: %s;pid: %s" %
                             (current_date,nginx_start_data,nginx_path,nginx_pid)
                             )
            status = True
        else:
            dead_pid = self.read_pid()
            self.logger.warning("current_time: %s; nginx is dead, nginx pid is %s try restart nginx." %
                                (current_date,dead_pid)
                                )
        return status
    def start_nginx(self):
        """启动nginx"""
        cmd = "/usr/sbin/nginx"
        cmd_result = os.system(cmd)
        if cmd_result == 0:
            self.check_nginx_run()
        else:
            self.logger.error("start nginx error")
    @staticmethod
    def main(log_name):
        """入口文件"""
        nginx_obj = Nginx_listen()
        nginx_obj.setup_log = log_name
        result = nginx_obj.check_nginx_run()
        if result:
            sys.exit(0)
        else:
            nginx_obj.start_nginx()
log_name = "nginx"
nginx_obj = Nginx_listen().main(log_name)
posted @ 2020-02-27 20:52  是阿凯啊  阅读(455)  评论(0编辑  收藏  举报