Linux中使用Python脚本监控项目,重启,关闭Tomcat

项目经常崩掉,就需要手动重启Tomcat,这时候就需要个脚本监控.

#!/usr/bin/python3
# coding=utf-8
'''
通过访问url检测项目是否正常运行,若不正常则重启Tomcat.
'''
import requests
import time
import os
import json
import psutil
import logging


Config.configLogging()
# 要检查的url
url = "输入请求的url"


# 关闭tomcat
def stopTomcat():
    pids = getPids("apache-tomcat")
    if pids is None:
        logging.info("未发现Tomcat进程")
        return

    for pid in pids:
        logging.info("开始中止Tomcat进程,tomcat进程id: "+str(pid))
        os.system("kill -9 " + str(pid))
    
    # 等待关闭完成
    while(True):
        pids = getPids("apache-tomcat")
        if pids is None or len(pids) == 0:
            return
        
        time.sleep(1)  # 休眠1秒再次检查
    logging.info("Tomcat进程中止完毕")

# 启动tomcat
def startTomcat():
    logging.info("开始Tomcat重启")
    os.system("/root/apache-tomcat-7.0.96/bin/startup.sh")

    # 等待重启成功
    t = 0
    while(True):
        if checkWeb() == False:
            time.sleep(5)  # 休眠5秒来等待启动服务器
            t = t + 5
        elif t >= 30:
            return
        else:
            # 启动完成
            return

    logging.info("Tomcat重启完毕")

# 检查系统是否还存活 true 还存活, false 已经关闭
def checkWeb():
    try:
        result = True
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0'}
        data = {"username":"shezhi@qq.com", "password":"shezhi1234"}
        # 请求超时时间为10秒
        response = requests.post(url, data)
        html = response.text
        print(str(getDate()) + "  响应数据:" + html)
        j = json.loads(html)['resCode']
        # encode = response.encoding # 从http header 中猜测的相应内容编码方式
        code = response.status_code # http请求的返回状态,若为200则表示请求成功,返回的状态码是 int类型
        print(str(getDate()) + "  检测到请求状态编码:" + str(code))
        result = (code == 200 and j is not None)
    except:
        result = False
    return result

# 获取时间
def getDate():
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    return now

# 获取命令行中包含指定关键字的进程id
def getPids(key : str):
    if key is None or len(key.strip()) == 0:
        return None

    pids = []
    # 查看系统全部进程
    for pnum in psutil.pids():
        p = psutil.Process(pnum)

        cmd = ' '.join(p.cmdline())

        if key not in cmd:
            continue

        pids.append(p.pid)
        print("pid : " + str(p.pid) + " cmd is : " + cmd)

    return pids

#获取当前文件名
def getFileName():
    file_name = os.path.basename(__file__).split('.')[0]
    return file_name

def mainApp():
    fileName = getFileName()
    myIds = getPids(fileName)
    print("本程序是 %s 进程数量 %d " % (fileName, len(myIds)))
    if myIds is not None and len(myIds) >= 3:
        return

    print(str(getDate()) + " =========开始检测系统状态=============")
    if checkWeb() == False:
        print(str(getDate()) + "  系统异常中·············")
        stopTomcat()
        
        startTomcat()
    else:
        print(str(getDate()) + "  ***系统正常***")

    print(str(getDate()) + "  =========结束检测系统状态=============")

mainApp()

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值