#!/bin/sh # function:自动监控tomcat进程,挂了就执行重启操作 # author:huanghong # DEFINE #获取环境变量 HOME=$ETC_HOME # 获取tomcat PPID TomcatID=$(ps -ef |grep tomcat |grep -w ‘tomcat‘|grep -v ‘grep‘|awk ‘{print $2}‘) #获取端口号if($4>20) 打印出的 端口为80 {if($4<20000)打印的为 127.0.0.1 80 | sed ‘s/ //g‘ 去除字符串的空格 port=`netstat -antup |grep LISTEN | grep ${TomcatID} | sed ‘s/ //g‘| awk -F ‘:‘ ‘{if($4>20) {print $4}}‘` # tomcat_startup tomcat启动路径 StartTomcat=$HOME/ETC_Managent/apache-tomcat/bin/startup.sh # 清理tomcat缓存 TomcatCache=$HOME/ETC_Managent/apache-tomcat/work # 定义要监控的页面地址 WebUrl=http://localhost:$port/depot/TestServlet #无底洞,不输出。 GetPageInfo=/dev/null # 日志输出 TomcatMonitorLog=$HOME/ETC_Controller/sbin/CheckStatus.log Monitor() { echo "[info]开始监控tomcat...[$(date +‘%F %H:%M:%S‘)]" if [ $TomcatID ];then echo "[info]tomcat进程ID为:$TomcatID." # 获取返回状态码 TomcatServiceCode=$(curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $WebUrl -w %{http_code}) if [ $TomcatServiceCode -eq 200 ];then echo "[info]返回码为$TomcatServiceCode,tomcat启动成功,页面正常." else echo "[error]访问出错,状态码为$TomcatServiceCode,错误日志已输出到$GetPageInfo" echo "[error]开始重启tomcat" kill -9 $TomcatID # 杀掉原tomcat进程 sleep 3 #rm -rf $TomcatCache # 清理tomcat缓存 $StartTomcat fi else echo "[error]进程不存在!tomcat自动重启..." echo "[info]$StartTomcat,请稍候......" #rm -rf $TomcatCache $StartTomcat fi echo "------------------------------" } Monitor>>$TomcatMonitorLog
??xshell 脚本
编写定时器:
crontab -e 如果没有crontab 请自行安装
将??写入 crontab -e 中
*/5 * * * * /usr/local/tomcat/TestStatus.sh ------>5分钟检查一次