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 | grep3306
- # Lsof-I:3306
- MYSQLPORT = '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> &1
- If[$? -Ne0]
- Then
- RestartMysqlService
- If["$ MYSQLPORT"="3306"]; Then
- Echo"Mysql restart successful ......"
- Else
- Echo"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/mysqlerr
- Fi
- Else
- Echo"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-9
- Service mysql start
- }
- If["$ MYSQLPORT"="3306"]
- Then
- CheckMysqlStatus
- Else
- RestartMysqlService
- Fi
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.