shell指令碼:監控MySQL服務是否正常

來源:互聯網
上載者:User

shell指令碼:監控MySQL服務是否正常

監控MySQL服務是否正常,通常的思路為:檢查3306連接埠是否啟動,ps查看mysqld進程是否啟動,命令列登入mysql執行語句返回結果,php或jsp程式檢測(需要開發人員開發程式)等等;

方法1:監聽3306連接埠

#!/bin/bash
#written by bkjia@2015-10-15
 
port=`netstat -nlt|grep 3306|wc -l`
if [ $port -ne 1 ]
then
 /etc/init.d/mysqld start
else
 echo "MySQL is running"
fi

方法2:查看mysqld進程

注意注意:如果使用進程過濾的話,指令碼名稱如果裡麵包含mysql的話,指令碼執行有坑,切記!!!因為會把指令碼也grep了一次,導致結果不準確;

[root@localhost baby]# cat check_mysql.sh
#!/bin/bash
#written by bkjia@2015-10-15
 
process=`ps -ef |grep mysql|grep -v grep |wc -l`
if [ $process -ne 2 ]
then
 /etc/init.d/mysqld start
else
 echo "MySQL is running"
fi

執行結果如下:

[root@localhost baby]# sh check_mysql.sh

Starting MySQL SUCCESS!

改名之後執行為正常結果:

[root@localhost baby]# mv check_mysql.sh check_db.sh

[root@localhost baby]# sh check_db.sh

MySQL is running

方法3:雙保險,進程和連接埠都成功才算mysql服務正常

#!/bin/bash
#written by bkjia@2015-10-15
 
port=`netstat -nlt|grep 3306|wc -l`
process=`ps -ef |grep mysql|grep -v grep |wc -l`
if [ $port -eq 1 ] && [ $process -eq 2 ]
then
    echo "MySQL is running"
else
    /etc/init.d/mysqld start
fi

4:使用用戶端登入mysql執行命令,查看返回結果測試服務是否啟動,理論上此方法最可靠。

[root@localhost baby]# cat check_db_client.sh
#!/bin/bash
#written by bkjia@2015-10-15
 
mysql -uroot -p123456 -e "select version();" &>/dev/null
if [ $? -ne 0 ]
then
 /etc/init.d/mysqld start
else
 echo "MySQL is running"
fi

執行結果如下:

[root@localhost baby]# sh check_db_client.sh

MySQL is running

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.