mysql主从同步监控脚本,利用mysql从库中的IO和SQL进程以及延迟时间来监控主从同步是否正常,详细shell脚本如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/bin/bash
#author wangning
#date 2017-7-17
#qq 1198143315
#Email 1198143315@qq.com
 
 
################################## define variable#############################
define_variable(){
ip=` ifconfig | sed  -n  '2p' | awk  -F  "[: ]+"  '{print $4}' `
code=(1158 1159 1008 1007 1062)
status=(`mysql -uroot -p123456 -S  /data/3309/mysql .sock -e  "show slave status\G" | egrep  "Running|Behind_Master|Last_Errno" | awk  '{print $2}' `)
}
 
############################ judge master #######################################
judge_master(){
mysql -uroot -p123456 -S  /data/3306/mysql .sock -e  "show databases"  &> /dev/null
if  [ $? - ne  0 ]; then
    echo  "ip $ip the master mysql service is downed"  > /mail/mysql_master .log &&\
    mail -s  "wangning tile"  1198143315@qq.com < /mail/mysql_master .log
else
    echo  "ip $ip the master mysql service is normal"  > /mail/mysql_master .log &&\
    mail -s  "wangning tile"  1198143315@qq.com < /mail/mysql_master .log
fi
}
 
################### judge IO SQL status and delay time ############################### 
IO_SQL_delay(){
if  "${status[0]}"  ==  "Yes"  -a  "${status[1]}"  ==  "Yes"  -a ${status[3]} - le  60 ]; then
    echo  "the master and slave replication is normal"  > /mail/mysql_slave .log &&\
    mail -s  "wangning tile"  1198143315@qq.com < /mail/mysql_slave .log
else 
    echo  "the master and slave replication is failed"  > /mail/mysql_slave .log &&\
    mail -s  "wangning tile"  1198143315@qq.com < /mail/mysql_slave .log
fi
}
 
################################ judge error code ##################################
judge_error_code(){
for  ((i=0;i<=${ #status[*]};i++))
do
if  [ ${status[2]} - eq  ${code[i]} ]; then
    mysql -uroot -p123456 -S  /data/3309/mysql .sock -e  "stop slave;set global sql_slave_skip_counter=1;start slave"
fi
done
}
 
main(){
while  true
do
define_variable
judge_master
IO_SQL_delay
judge_error_code
sleep  180
done
}
 
main