Note: This article is from the blog "afei". If you want to repost this article, please contact the author! And indicate the source: http://blog.csdn.net/faye0412/article/details/7884245
I have contributed a script to monitor the MySQL process. I hope it will be helpful to you.
Function:
Monitors the MySQL process and restarts upon failure. If the MySQL process fails to be started, an email notification is sent.
The Code is as follows:
#!/bin/bash#/usr/bin/nmap localhost | grep 3306#lsof -i:3306MYSQLPORT=`netstat -na|grep "LISTEN"|grep "3306"|awk -F[:" "]+ '{print $5}'`function checkMysqlStatus(){/usr/bin/mysql -uroot -p11111 --connect_timeout=5 -e "show databases;" &>/dev/null 2>&1if [ $? -ne 0 ]thenrestartMysqlServiceif [ "$MYSQLPORT" == "3306" ];thenecho "mysql restart successful......" elseecho "mysql restart failure......"echo "Server: $MYSQLIP mysql is down, please try to restart mysql by manual!" > /var/log/mysqlerr#mail -s "WARN! server: $MYSQLIP mysql is down" admin@yourdomain.com < /var/log/mysqlerrfielseecho "mysql is running..."fi}function restartMysqlService(){echo "try to restart the mysql service......"/bin/ps aux |grep mysql |grep -v grep | awk '{print $2}' | xargs kill -9service mysql start}if [ "$MYSQLPORT" == "3306" ]thencheckMysqlStatuselserestartMysqlServicefi
We recommend that you run the task every 10 minutes.
*/10 * root/bin/sh/root/mysql_status.sh
Principle:
1) Check whether port 3306 of MySQL is normal;
2) use the account to connect to the database and execute the show databases command;
3) if the above two points work properly, the database is running normally.
In addition, you can monitor the myaql port in three ways:
1)/usr/bin/NMAP localhost | grep 3306
2) lsof-I: 3306
3) netstat-Na | grep "listen" | grep "3306" | awk-f [: ""] + '{print $5 }'
The third type is used here. Note: The operating systems '{print $5}' may be different. Please test them on your own. If you use the first method, you need to install NMAP.