mysql_listen.sh:
1 2 3 4 5 6 7 8 9 10 |
#!/bin/bash pgrep -x mysql &> /dev/null if [ $? -ne 0 ] then echo "At time: `date` :MySQL is stop .">> /var/log/mysql_messages service mysql start #echo "At time: `date` :MySQL server is stop." else echo "MySQL server is running ." fi |
该脚本实现监测mysql的状态,如果发现mysql停止,则自动启动,并填写停止时间
我认为还有一种更好的方式,不同与原作者
我使用的是wdcp面板使用上面的代码会无法读取到日志,所以就使用了检测pgrep mysqld的方法。
1 2 3 4 5 6 7 8 9 |
#!/bin/bash pgrep mysqld &> /dev/null if [ $? -gt 0 ] then echo "`date` mysql is stop" service mysql start else echo "`date` mysql running" fi |
使用 pgrep mysqld 监测mysqld服务的运行状态,其中&> /dev/null 是将其结果输出到空文件,也就是不保存输出信息
$? 是拿到上一条命令的运行结果,-gt 0 是判断是否大于0,后面则是输出时间到日志文件,然后启动mysql,否则不启动mysql
我的测试步骤如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
[root@iz62glfi9kulmwz ~]# pgrep mysql 3375 3924 [root@iz62glfi9kulmwz ~]# pgrep mysqld &> /dev/null [root@iz62glfi9kulmwz ~]# if [ $? -gt 0 ] > then > echo "`date` mysql is stop" > service mysql start > else > echo "`date` mysql running" > fi Fri Aug 11 13:38:20 CST 2017 mysql running [root@iz62glfi9kulmwz ~]# /www/sh/mysql.sh -bash: /www/sh/mysql.sh: Permission denied [root@iz62glfi9kulmwz ~]# /www/sh/mysql.sh Fri Aug 11 13:41:05 CST 2017 mysql running [root@iz62glfi9kulmwz ~]# service mysql stop Redirecting to /bin/systemctl stop mysql.service [root@iz62glfi9kulmwz ~]# /www/sh/mysql.sh Fri Aug 11 13:41:43 CST 2017 mysql is stop Redirecting to /bin/systemctl start mysql.service [root@iz62glfi9kulmwz ~]# |
出现Permission denied的原因是mysql.sh权限问题,把其设置为0777即可。
日志输出
1 2 3 4 5 6 7 8 9 |
#!/bin/bash pgrep mysqld &> /dev/null if [ $? -gt 0 ] then echo "`date` mysql is stop" >> /var/log/mysql_listen.log service mysql start else echo "`date` mysql running" >> /var/log/mysql_listen.log fi |
即每执行一次脚本,输出结果都会被保存到 /var/log/mysql_listen.log 中
同理:我们可以实现nginx的停止自动重启
pgrep mysql &> /dev/null
只需要把mysql改为nginx即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
[root@iz62glfi9kulmwz ~]# pgrep nginx 15788 15789 15791 15792 [root@iz62glfi9kulmwz ~]# service nginxd stop Stopping nginxd (via systemctl): [ OK ] [root@iz62glfi9kulmwz ~]# pgrep nginx [root@iz62glfi9kulmwz ~]# #!/bin/bash [root@iz62glfi9kulmwz ~]# pgrep nginx &> /dev/null [root@iz62glfi9kulmwz ~]# if [ $? -gt 0 ] > then > echo "`date` nginx is stop" > service nginxd start > else > echo "`date` nginx running" > fi Sat Aug 12 14:44:06 CST 2017 nginx is stop Starting nginxd (via systemctl): [ OK ] [root@iz62glfi9kulmwz ~]# |
二 使脚本每隔一定的时间自动运行
linux上定期执行脚本用的是cron进程
命令:
1 2 |
crontab -e #第一次使用cron,得用序号选择编辑器 |
在最后一行加入:
1 |
5 * * * * /www/sh/mysql.sh |
*/5表示分钟能被5整除,及每5分钟执行一次,后面4个*号,分别表示 小时,日,月,星期。
保存后退出。
重启cron就可以了
1 |
service cron restart |
这样就会每隔5分钟,执行一次检测mysql的脚本。
原文链接:
http://www.embbnux.com/2014/07/08/shell_listen_mysq_auto_restart/
历史上的今天:
- 2016: 呵呵!腾讯cdn被阿里拦截( 0)
- 2015: 使用javascript为WordPress添加夜间模式( 5)
- 2015: PHP实现获取文件后缀名的几种常用方法( 0)
除特别注明外,本站文章均采用BY-NC-SA协议授权,转载请注明来自:http://www.embbnux.com/2014/07/08/shell_listen_mysq_auto_restart/