Snippets

Kunzhipeng Linux下确保指定的服务(必须配置为服务)处于运行状态

Created by Qi Peng last modified
# coding: utf-8
# keep_service_running.py
# 确保指定的服务(必须配置为服务)在运行,如果未启动则启动
# 结合root用户的计划任务使用 e.g.
# */5 * * * * /usr/bin/python /root/keep_service_running.py squid squid > /root/keep_service_running.output 2>&1
# */5 * * * * /usr/bin/python /home/qi/kp-pppoe-proxies/keep_service_running.py tinyproxy tinyproxy > /home/qi/kp-pppoe-proxies/keep_service_running.output 2>&1
# 用法:
# /usr/bin/python keep_service_running.py tinyproxy tinyproxy
# 命令行参数有2个, 第一个为进程名, 第二个为服务名

import sys
import os
import time
import subprocess

def check_output(*popenargs, **kwargs):
    r"""Run command with arguments and return its output as a byte string.
    Backported from Python 2.7 as it's implemented as pure python on stdlib.
    >>> check_output(['/usr/bin/python', '--version'])
    Python 2.6.2
    兼容Python 2.6
    """
    process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
    output, unused_err = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        error = subprocess.CalledProcessError(retcode, cmd)
        error.output = output
        raise error
    return output

def keep_service_run(process, service):
    """判断指定进程是否存在,如果不存在则启动相应服务
    process - 要检测的进程名;
    service - 要启动的服务名;
    """
    print '[%s]Checking whether service "%s" is running...' % (time.strftime('%Y-%m-%d %H:%M:%S'), service)
    try:
        cmd_result = check_output(['ps', 'aux'])
    except Exception, e:
        print '"ps aux" FAIL. %s %s' % (exc.returncode, exc.output)
    else:
        running = False
        for line in cmd_result.splitlines():
            if os.path.basename(__file__) not in line:
                # 跳过本脚本进程
                if process in line:
                    running = True
                    break
        if running:
            # 服务还在运行
            print '[Running]Service "%s" is still running.' % (service,)
        else:
            # 服务没在运行,尝试启动
            print '[Stopped]Service "%s" is stopped, will start it.' % (service,)
            os.system('sudo service %s start' % (service,))
            
if __name__ == '__main__':
    try:
        process, service = sys.argv[1], sys.argv[2]
    except IndexError:
        print 'Usage: python keep_service_run.py process-name service-name'
    else:
        keep_service_run(process=process, service=service)

Comments (0)