1、vi /root/sh/mysql_status.sh创建文件,脚本粘贴进去(脚本见后面)(如果是windows编辑上传的,可能存在编码问题)
2、设置执行权限
chmod -R 777 /root/sh
chown -R user:user /root/sh
3、crontab -e添加到定时,1分钟执行一次
*/1 * * * * root /bin/sh /root/sh/mysql_status.sh
脚本如下:
#!/bin/bash
#/usr/bin/nmap localhost | grep 3306
#lsof -i:3306
MYSQLPORT=`netstat -na|grep "LISTEN"|grep "3306"|awk -F[:" "]+ '{print $4}'`
function checkMysqlStatus(){
/usr/bin/mysql -uroot -p111111 --connect_timeout=5 -e "show databases;" &>/dev/null 2>&1
if [ $? -ne 0 ]
then
restartMysqlService
if [ "$MYSQLPORT" == "3306" ];then
echo "mysql restart successful......"
else
echo "mysql restart failure......"
echo "Server: $MYSQLIP mysql is down, please try to restart mysql by manual!" > /var/log/mysqlerr
#mail -s "WARN! server: $MYSQLIP mysql is down" admin@yourdomain.com < /var/log/mysqlerr
fi
else
echo "mysql is running..."
fi
}
function restartMysqlService(){
echo "try to restart the mysql service......"
/bin/ps aux |grep mysql |grep -v grep | awk '{print $2}' | xargs kill -9
#service mysql start
systemctl restart mysqld
}
if [ "$MYSQLPORT" == "3306" ]
then
checkMysqlStatus
else
restartMysqlService
fi
Coding in the rain, coding anywhere, coding my life.
懂一些前端,懂一些后端,是程序猿,也是产品狗,关注大数据、关注人工智能、关注一切有意思的东西。
我是raincoding,喜欢就关注我吧。
网友评论