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 @   是阿凯啊  阅读(469)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示