#自动检测某个tomcat状态(w精确匹配 v去除某种进程 awk数据处理 print $2 打印第二列)
TomcatID=$(ps -ef |grep -w 'apache-tomcat-7.0.81'|grep -v 'grep'|awk '{print $2}')
# tomcat启动程序(这里注意tomcat实际安装的路径)
StartTomcat=/usr/local/apache-tomcat-7.0.81/bin/startup.sh
TomcatCache=/usr/local/apache-tomcat-7.0.81/work
# 定义要监控的页面地址,建议跟上具体项目xxx ,建议 具体到某个页面或接口
TomcatUrl=http://localhost:8080
# 日志输出,根据实际情况设置路径,并创建文本
#页面日志
GetPageInfo=/usr/local/zhangwk/logs/tomcatMonitorPage.info
#tomcat进程日志
TomcatMonitorLog=/usr/local/zhangwk/logs/tomcatMonitor.log
MonitorTomcat()
{
echo "[info]开始监控tomcat...[$(date +'%F %H:%M:%S')]"
if [ $TomcatID ];then # 这里判断TOMCAT进程是否存在
echo "[info]当前tomcat进程ID为:$TomcatID,继续检测页面..."
# 检测是否启动成功(成功的话页面会返回状态"200")
TomcatServiceCode=$(curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $TomcatUrl -w %{http_code})
if [ $TomcatServiceCode -eq 200 ];then
echo "[info]页面返回码为$TomcatServiceCode,tomcat启动成功,测试页面正常......"
else
echo "[error]tomcat页面出错,请注意......状态码为$TomcatServiceCode,错误日志已输出到$GetPageInfo"
echo "[error]页面访问出错,开始重启tomcat"
kill -9 $TomcatID # 杀掉原tomcat进程
sleep 3
rm -rf $TomcatCache # 清理tomcat缓存
$StartTomcat # 启动tomcat
fi
else
echo "[error]tomcat进程不存在!tomcat开始自动重启..."
echo "[info]$StartTomcat,请稍候......"
rm -rf $TomcatCache # 清理tomcat缓存
$StartTomcat # 启动tomcat
fi
echo "------------------------------"
}
MonitorTomcat >>$TomcatMonitorLog
chmod +x test.sh
crontab -e
*/5 * * * * /usr/local/zhangwk/test.sh