各写一个shell和python脚本来监控http请求,并在服务不可用的时候重启服务。

监控的连接为:

http://192.168.1.101:5022/product

http://192.168.1.101:5024/module

shell脚本如下,配合crontab计划任务每一分钟执行一次检查:

#!/bin/bash
# This shell is used to moniter 192.168.1.101 port 5022 & 5024
date  #在crontab里用来记录log的时间
i=0
curl -s -m 10 192.168.1.101:5022/product > /dev/null  #用crul测试服务是否可用
n=`echo $?`  #只有在服务请求正常的情况下$?的值才为0
echo "5022 curl echo $n"
curl -s -m 10 192.168.1.101:5024/module > /dev/null
m=`echo $?`  
echo "5024 curl echo $m"
if [[ "$n" -eq "$i" && "$m" -eq "$i" ]]; then
	echo "api port 5022 and 5024 is ok."
else
	echo "service need restart"
	/etc/init.d/serverapi restart
fi

python脚本,每隔十秒诊断一次:

import requests
import os
import time
from datetime import datetime, timedelta

def restart():
    try:
        urls = ['http://192.168.1.101:5022/product', 'http://192.168.1.101:5024/module']
        while True:
#            import pdb
#            pdb.set_trace()
            sleep = 10
            for url in urls:
                print('get %s'%url)
                r = requests.get(url,timeout=10)
                if r.status_code == 200:
                    print('%s is ok...'%url)
                    print('moniter continue after 10s')
            time.sleep(sleep)
    except Exception as e:
        print(e.message)
        print('%s is ERROR !!!'%url)
        print('consoleapi will be restart')
        os.system('/etc/init.d/serverapi stop')
	print('consoleapi stoped')
        time.sleep(6)
        os.system('/etc/init.d/serverapi start')
if __name__ == '__main__':
    print('main')
    def main():
      while True:
            restart()
    main()

两个脚本写的都挺烂,呵呵。贴出来主要是提醒自己,用shell或者用Python怎么方便怎么用,不要太拘泥于形式。