cyrus 发表于 2015-8-10 12:06:17

Tomcat 自动监控脚本

  来源:
http://hi.baidu.com/myfreezone/blog/item/96e8ad1ed502dd1e40341751.html

本脚本监控Tomcat服务,当服务死掉后脚本自动重启服务。
  1、将本脚本保存为/root/tcautorestart.sh,并给执行权限。
  #!/bin/bash
if [[ -e /root/tcstatus.log ]];then
cp -f /dev/null /root/tcstatus.log
fi
/usr/local/bin/lynx -dump -connect_timeout=15000 -error_file=/root/tcstatus.log      \
http://downtheme.somode.com:8080/index.jsp         >/dev/null         ##index.jsp为用于测试的jsp页
cat /root/tcstatus.log | grep "STATUS=HTTP/1.1 200 OK" >/dev/null
  if (( $? != 0 ));then
{
#shutdown tomcat
date >> /root/tcrestart.log
while true
do
/usr/local/tomcat/bin/shutdown.sh         >> /root/tcrestart.log
sleep 20
cp -f /dev/null /root/process.tc
ps -aux | awk '$0 ~ /java.*tomcat/{print $0}' > /root/process.tc
cat process.tc | grep "java.*tomcat" > /dev/null
if (( $? == 0 ));then
         continue
else
{
         echo "Tomcat shutdown success!" >> /root/tcrestart.log
         break
}
fi
done
  #startup tomcat
while true
do
/usr/local/tomcat/bin/startup.sh         >> /root/tcrestart.log
sleep 5
cp -f /dev/null /root/process.tc
ps -aux | awk '$0 ~ /\/bin\/java/{print $0}' > /root/process.tc
cat process.tc |grep "/bin/java" > /dev/null
if (( $? == 0 ));then
{
         echo "Tomcat restartup success!" >> /root/tcrestart.log
         break
}
else
continue
fi
done
}
else
exit 0
fi

2、安装lynx
# tar -xzvf lynx2.8.5.tar.gz
# cd ynx2.8.5
# make
# make install         ##lynx默认安装到/usr/local/lynx下
# ln -s /usr/local/lynx /bin         ##注意自动化任务的path变量和bash的可能不同,
                        ##一个能在bash中运行的很好的脚本不一定在cron中运行的很好,有些命令可能在cron中找不到
3、将tomcat自启动脚本加到cron中
# crontab -e
#tomcat auto restart自动重启
*/5 * * * * /root/tcautorestart.sh > /dev/null 2>&1
  参考:
  得到网页的返回状态:

# lynx -dump -connect_timeout=15000 -error_file=/root/test1.log \
http://downtheme.somode.com:8080/index.jsp

          0                     ##显示浏览页的内容

# less /root/test1.log                ##网页的返回状态信息
  URL=http://downtheme.somode.com:8080/index.jspdf (GET)
STATUS=HTTP/1.1 404 /index.jspdf         ##网页不存在,返回404错误
  URL=http://downtheme.somode.com:8080/index.jsp (GET)
STATUS=HTTP/1.1 200 OK                  ##网页能正常访问
  lynx参数:
         -dump :显示网页内容到标准输出并推出
         -connect_timeout :设置超时时间,单位(毫秒)
         -error_file :将网页的返回状态信息写进文件
页: [1]
查看完整版本: Tomcat 自动监控脚本