參考來源:http://my.oschina.net/chinaearl/blog/111830shell
# func:自動監控tomcat腳本而且執行重啓操做 # tomcat啓動程序(這裏注意tomcat實際安裝的路徑) StartTomcat=/myzone/apache-tomcat-7.0.56/bin/startup.sh TomcatCache=/myzone/apache-tomcat-7.0.56/tomcatCache # 定義要監控的頁面地址 WebUrl=http://localhost:8080/ # 日誌輸出 GetPageInfo=/myzone/apache-tomcat-7.0.56/null TomcatMonitorLog=/myzone/apache-tomcat-7.0.56/TomcatMonitor.log Monitor() { echo "[info]開始監控tomcat...[$(date +'%F %H:%M:%S')]" # 獲取tomcat進程ID while(true) do TomcatID=$(ps -ef |grep tomcat |grep -w '\/myzone\/apache-tomcat-7.0.56\/conf'|grep -v 'grep'|awk '{print $2}') if [ $TomcatID ];then # 這裏判斷TOMCAT進程是否存在 echo "[info]當前tomcat進程ID爲:$TomcatID,繼續檢測頁面..." # 檢測是否啓動成功(成功的話頁面會返回狀態"200") 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]tomcat頁面出錯,請注意......狀態碼爲$TomcatServiceCode,錯誤日誌已輸出到$GetPageInfo" echo "[error]頁面訪問出錯,開始重啓tomcat" kill -9 $TomcatID # 殺掉原tomcat進程 rm -rf $TomcatCache # 清理tomcat緩存 $StartTomcat fi else echo "[error]tomcat進程不存在!tomcat開始自動重啓..." echo "[info]$StartTomcat,請稍候......" rm -rf $TomcatCache $StartTomcat fi echo "------------------------------" sleep 60 done } Monitor>>$TomcatMonitorLog