项目经常崩掉,就需要手动重启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":"[email protected]", "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()