监听3306端口

发布时间:2015-12-14 15:34:07编辑:丝画阁阅读(702)

方法1:监听3306端口

#!/bin/bash
#written by linuxidc@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

方法2:查看mysqld进程

注意注意:如果使用进程过滤的话,脚本名称如果里面包含mysql的话,脚本执行有坑,切记!!!因为会把脚本也grep了一次,导致结果不准确;

[root@localhost baby]# cat check_mysql.sh
#!/bin/bash
#written by linuxidc@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

执行结果如下:

[root@localhost baby]# sh check_mysql.sh

Starting MySQL SUCCESS!

改名之后执行为正常结果:

[root@localhost baby]# mv check_mysql.sh check_db.sh

[root@localhost baby]# sh check_db.sh

MySQL is running

方法3:双保险,进程和端口都成功才算mysql服务正常

#!/bin/bash
#written by linuxidc@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:使用客户端登录mysql执行命令,查看返回结果测试服务是否启动,理论上此方法最可靠。

[root@localhost baby]# cat check_db_client.sh
#!/bin/bash
#written by linuxidc@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

执行结果如下:

[root@localhost baby]# sh check_db_client.sh

MySQL is running

关键字