LINUX script listens to MYSQL

Method 1: monitor mysql port and process

As a novice reference, the code is as follows:

#!/bin/bash
#liud
#function: monitor mysql status, and start mysql in case of exception
LOG_DIR=/data/monitor/
EMAIL_PATH=/server/scripts/email.txt
LOG_FILE=mysql_`date +%Y-%m-%d`.log
NowTime=`date +%Y-%m-%d_%H:%M:%S`
DB_PATH=/etc/init.d/mysql
# Log directory does not exist, create
[ ! -d $LOG_DIR ] && mkdir -p $LOG_DIR
# Check the monitoring port of mysql 3306 and convert wc-l to number
portNum=`netstat -lnt|grep 3306|wc -l`
# View the process of mysql and convert wc-l to number
mysqlProcessNum=`ps -ef|grep mysql|grep -v grep|wc -l`
if [ $portNum -eq 1 ] && [ $mysqlProcessNum -eq 2 ];then
	# >>$log? Dir / $log? File appends the current status of mysql to the log file
	echo "${NowTime}, db is running." >>$LOG_DIR/$LOG_FILE
else
	# >>$log? Dir / $log? File appends the current status of mysql to the log file
	echo "--${NowTime}, db is not running.--" >>$LOG_DIR/$LOG_FILE
	# service mysql start >>$LOG_DIR/$LOG_FILE && status="success"||status="failure"
	# mysql start 
	${DB_PATH} start>/dev/null
	# Wait 30 seconds for status
	sleep 30
	# Review mysql ports and processes
	portNum=`netstat -lnt|grep 3306|wc -l`
	mysqlProcessNum=`ps -ef|grep mysql|grep -v grep|wc -l`
	if [ $portNum -ne 1 ] || [ $mysqlProcessNum -ne 2 ];then
		# If the restart fails, the $? Will return 1 after the process of violent killing mysql is completed. The corresponding is that there is no process to kill, jump out of the loop and start mysql again
		while true
		do
			echo "${NowTime},killall mysqld.">>$LOG_DIR/$LOG_FILE
			killall mysqld >/dev/null 2>&1
			[ $? -ne 0 ] && break
			sleep 1
		done
		#The service mysql start script can be started directly, but it can't be put in crond. I don't understand why
		${DB_PATH} start>/dev/null&& status="success"||status="failure"
	else
		status="success"
	fi
	# Append mysql startup status to log file
	echo "${NowTime},mysql startup status is $status.">> $LOG_DIR/$LOG_FILE
	#Send email prompt
	for email_num in `cat $EMAIL_PATH`
	do
		mail -s "${NowTime},mysql startup status is $status." $email_num <$LOG_DIR/$LOG_FILE
	done
fi

The defect of the above script is that although MySQL is started, it may not be able to connect normally, for example, the mount is full, the database is locked, and so on. The best way is to simulate whether the user can connect to the database normally to judge whether the database is normal at present. I will talk about it later


Tags: MySQL Database

Posted on Sat, 02 May 2020 00:58:57 -0700 by no_maam