如何让nginx执行python代码_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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值