开发监控MySQL数据库的脚本
脚本1:
cat check_mysql_01.sh
#!/bin/bash
echo method1----------------------
if [ `netstat -antlpe|grep 3306|awk -F "[ :]+" '{print $5}'` -eq 3306 ];then echo "MySQL is running."
else
echo "MySQL is stopping" /etc/init.d/mysqld start
fi
关闭mysql
/etc/init.d/mysqld stop
注意:
1.最好不要用整数进行比较,因为一旦端口不存在,取值就为空,进行整数比较就会报错
2.不要根据列取具体的值,而是要过滤关键字,通过wc转成行数再判断
用字符串的方式进行比较就好多了,避免了脚本1中整数比较发生的错误
脚本2
#!/bin/bash
echo method2----------------------
if [ "`netstat -antlpe|grep 3306|awk -F "[ :]+" '{print $5}'`" = "3306" ];then echo "MySQL is running."
else
echo "MySQL is stopping" /etc/init.d/mysqld start fi
脚本3:
#!/bin/bash
echo method3----------------------
if [ `netstat -antlpe|grep mysql|wc -l` -gt 0 ];then echo "MySQL is running."
else
echo "MySQL is stopping" /etc/init.d/mysql start
fi
脚本4:
#!/bin/bash
echo method4--------------------if [ `lsof -i tcp:3306|wc -l` -gt 0 ];then
echo "MySQL is running."
else
echo "MySQL is stopping" /etc/init.d/mysql start
fi
脚本5:
#!/bin/bash
echo method5----------------------
[ `rpm -qa nmap|wc -l` -lt 1 ] && yum install nmap -y &>/dev/null if [ `nmap 127.0.0.1 -p 3306 2>/dev/null|grep open|wc -l` -gt 0 ];then echo "MySQL is running."
else
echo "MySQL is stopping" /etc/init.d/mysqld start
fi
脚本6
#!/bin/bash
echo method6----------------------
[ `rpm -qa nc|wc -l` -lt 1 ] && yum install nc -y &>/dev/null
if [ `nc -w 2 127.0.0.1 3306 &>/dev/null&&echo ok|grep ok|wc -l` -gt 0 ];then echo "MySQL is running."
else
echo "MySQL is stopping" /etc/init.d/mysqld start
fi
脚本7:
#!/bin/bash
echo method7-------------------------
if [ `ps -ef|grep -v grep|grep mysql|wc -l` -gt 0 ];then echo "MySQL is Running."
else
echo "MySQL is Stopping." /etc/init.d/mysqld start fi
采用传统的过滤进程的方法,grep -v grep是排除此命令自身
httpd的监控脚本
vim check_httpd.sh
#!/bin/bash
. /etc/init.d/functions rpm -qa httpd &>/dev/null if [ $? -eq 0 ];then echo "httpd is alreday install"
else
yum install httpd -y
fi if [ $# -lt 1 ];then
echo $"Usage: $0 {start|stop|restart|status}"
fi case "$1" in start) systemctl start httpd
if[ `netstat -antlpe | grep httpd |wc -l` -eq 1 ];then action "httpd is starting" /bin/true
fi
;;
stop)
systemctl stop httpd
if [ `netstat -antlpe | grep httpd |wc -l` -eq 0 ];then action "httpd is stopping" /bin/true
fi ;; restart)
if [ `netstat -antlpe | grep httpd |wc -l` -eq 0 ];then echo "httpd is already stop please input start" fi
if [ `netstat -antlpe | grep httpd | wc -l` -eq 1 ];then
pkill httpd && /etc/init.d/httpd start fi ;;
*)
echo $"Usage: $0 {start|stop|restart|status}"
;;
esac
sh check_httpd.sh stop