Shell script: monitor whether the MySQL service is normal
The general idea is to check whether the MySQL service is normal: Check whether port 3306 is started, ps to check whether the mysqld process is started, and run the command line to log on to mysql to execute the statement and return the result, php or jsp program detection (developers need to develop programs) and so on;
Method 1: Listen to port 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
Method 2: view the mysqld Process
Note: If you use process filtering, if the script name contains mysql, script execution is pitfall. Remember !!! The result is inaccurate because the script is grep once;
[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
The execution result is as follows:
[Root @ localhost baby] # sh check_mysql.sh
Starting MySQL SUCCESS!
After the name is changed, the result is displayed as follows:
[Root @ localhost baby] # mv check_mysql.sh check_db.sh
[Root @ localhost baby] # sh check_db.sh
MySQL is running
Method 3: The mysql service is normal only when both processes and ports are successful.
#! /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: Use the client to log on to mysql and run the command to check whether the returned result Test Service is started. Theoretically, this method is the most reliable.
[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
The execution result is as follows:
[Root @ localhost baby] # sh check_db_client.sh
MySQL is running
This article permanently updates the link address: