原理:
1)監(jiān)控MYSQL的運(yùn)行狀態(tài)昔园;
2)Slave機(jī)器的IO和SQL狀態(tài)都必須為YES,缺一不可阿浓;
注意,請(qǐng)結(jié)合自身的實(shí)際環(huán)境使用蹋绽。
ps:網(wǎng)上搜了下芭毙,大致都存在同一個(gè)坑,echo輸出的時(shí)候沒(méi)有注意默認(rèn)不轉(zhuǎn)義換行的問(wèn)題卸耘,會(huì)導(dǎo)致對(duì)Slave_SQL_Running的監(jiān)控失去意義退敦,實(shí)際上是把Slave_IO_Running的值重復(fù)監(jiān)控了。
#!/bin/sh
ip=eth0? #網(wǎng)卡名稱
mysql_binfile=/usr/bin/mysql
mysql_user=root? #MySQL數(shù)據(jù)庫(kù)賬號(hào)
mysql_pass=123456? #密碼
datetime=`date +"%Y-%m-%d/%H:%M:%S"`? #獲取當(dāng)前時(shí)間
mysql_slave_logfile=/var/log/mysql/check_mysql_slave.log? #日志文件路徑蚣抗,必須提前創(chuàng)建好
slave_ip=`ifconfig $ip|grep "inet " | awk -F[:" "]+ '{print $4}'`
status=$($mysql_binfile -u$mysql_user -p$mysql_pass -e "show slave status\G" | grep -i "running")
#驗(yàn)證方式:Slave_IO_Running=`echo -n "$status" | grep Slave_IO_Running | awk ' {print $1}'` (輸出Slave_IO_Running為正常)
Slave_IO_Running=`echo -n "$status" | grep Slave_IO_Running | awk ' {print $2}'`
#驗(yàn)證方式:Slave_IO_Running=`echo -n "$status" | grep Slave_SQL_Running | awk ' {print $1}'` (輸出Slave_SQL_Running為正常)
Slave_SQL_Running=`echo -n "$status" | grep Slave_SQL_Running | awk '{print $2}'` #網(wǎng)上有類似的代碼侈百,這里的echo應(yīng)該加-n參數(shù),并且變量應(yīng)加引號(hào)翰铡,否則不轉(zhuǎn)義換行符钝域,實(shí)際匹配出來(lái)的結(jié)果是Slave_IO_Running參數(shù)的值
if [ "$Slave_IO_Running" = "Yes" -a "$Slave_SQL_Running" = "Yes" ]
then
echo "Slave is Running!"
echo "$datetime $slave_ip Slave is Running!" >> $mysql_slave_logfile
else
echo "$datetime $slave_ip Slave is not running!"
echo "$datetime $slave_ip Slave is not running!" >> $mysql_slave_logfile
fi