进程端口监控,并重新启动

import os
import time
import socket
import subprocess
# 配置示例/etc/yayaw-agent.conf
# {
# 'DJANGO':['127.0.0.1', '81', 'cd /mssh/ && python36 manage.py runserver 0.0.0.0:81'],
# 'NGINX':['127.0.0.1', '443', '/opt/nginx/sbin/nginx']
# }
def check_host(ip, port):
    sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sk.settimeout(2)
    try:
        sk.connect((ip, int(port)))
        return 1
    except Exception:
        return 0
    sk.close()

def logs_write(content):
    f = open('/tmp/yayaw-agent.log', 'a+')
    f.write(time.strftime("%Y-%m-%d %H:%M:%S    ", time.localtime()) + content)

def task_exec():
    conf_file = '/etc/yayaw-agent.conf'
    logs_f = open('/tmp/yayaw-access.log', 'a+')
    if os.path.exists(conf_file):
        conf_f = open(conf_file)
        conf = conf_f.read()
    else:
        print('配置不存在')
        exit()
    docker_dic = eval(conf)
    for n in docker_dic:
        info = docker_dic[n]
        check_ip = info[0]
        check_port = info[1]
        check_exec = info[2]
        host_info = ('%s:%s' % (check_ip, check_port)).ljust(21, ' ')
        if check_host(check_ip, check_port) == 0:
            logs_write('%s异常重新启动 %s\n' % (host_info, n))
            subprocess.Popen(check_exec, shell=True, stdin=logs_f.fileno(), stdout=logs_f.fileno(), stderr=logs_f.fileno())
        elif check_host(check_ip, check_port) == 1:
            logs_write('%s正常连接状态 %s\n' % (host_info, n))
        else:
            logs_write('%s异常未知状态 %s\n' % (host_info, n))
    logs_f.flush()
    logs_f.close()
    time.sleep(30)

if __name__ == '__main__':
    pid = os.fork()
    if pid != 0:
        os._exit(0)
    while True:
        task_exec()