1. 程式人生 > >MySQL,nginx,tomcat檢查進程是否存在以及啟動

MySQL,nginx,tomcat檢查進程是否存在以及啟動

返回 date usr local 測試 mysql tmp 過濾 日誌輸出

vi mysql_mon.sh
#!/bin/bash
if [ netstat -tlunp|grep mysql|wc -l -gt 0 ] #過濾進程名為mysql,轉成數字
then
echo "MySQL is Running."
else
echo "MySQL is Stopped."
/etc/init.d/mysql start
fi

vi nginx_mon.sh
#!/bin/bash
if [ netstat -tlunp|grep nginx|wc -l -gt 0 ] #過濾進程名為nginx,轉成數字
then
echo "Nginx is Running."

else
echo "Nginx is Stopped."
/etc/init.d/nginx start
fi

vi tomcat_mon.sh
#!/bin/sh

func:自動監控tomcat腳本並且執行重啟操作

獲取tomcat進程ID

TomcatID=$(ps -ef |grep tomcat |grep -w ‘tomcat‘|grep -v ‘grep‘|awk ‘{print $2}‘)

tomcat啟動程序(這裏註意tomcat實際安裝的路徑)

StartTomcat=/usr/local/tomcat/bin/startup.sh
TomcatCache=/usr/local/tomcat/work

定義要監控的頁面地址

WebUrl=http://192.168.254.131:8080/

日誌輸出

GetPageInfo=/tmp/TomcatMonitor.Info
TomcatMonitorLog=/tmp/TomcatMonitor.log
Monitor()
{
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 $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進程  
    sleep 3  
    rm -rf $TomcatCache # 清理tomcat緩存  
    $StartTomcat  
fi  

else
echo "[error]tomcat進程不存在!tomcat開始自動重啟..."
echo "[info]$StartTomcat,請稍候......"
rm -rf $TomcatCache
$StartTomcat
fi
echo "------------------------------"
}
Monitor>>$TomcatMonitorLog

MySQL,nginx,tomcat檢查進程是否存在以及啟動