Centos7 定时监测应用并重启
系统服务器在运行过程中因需要时刻检测数据库和nginx等软件是否在正常工作,特编写脚本进行检测应用状态,并在应用出问题时进行重启。
因为监测时用到lsof命令,如提示lsof命令不存在,请自行安装命令
yum install lsof -y
检测应用状态脚本
#!/bin/bash
LOG_FILE="autostart.log"
#检测nginx
curtime=$(date "+%Y-%m-%d %H:%M:%S")
a=`lsof -i:80 |grep 'nginx' |grep -v grep |grep -v agent|sort | tail -1 | cut -f 1 -d ' '`
if [[ $a != 'nginx' ]]; then
echo "$curtime 系统检测到nginx,已挂掉,启动中...." >> autostart.log;
/usr/sbin/nginx #启动nginx命令
echo "$curtime nginx启动完成" >> autostart.log;
else
echo "$curtime 系统检测到nginx运行正常" >> autostart.log;
fi
#检测Redis
checkRedis=`lsof -i:6379 |grep 'redis-ser' |grep -v grep |grep -v agent|sort | tail -1 | cut -f 1 -d ' '`
if [[ $checkRedis != 'redis-ser' ]]; then
echo "$curtime 系统检测到Redis已挂掉,启动中...." >> autostart.log;
/home/software/redis/redis-4.0.2/src/redis-server /home/software/redis/redis-4.0.2/redis.conf #启动redis
echo "$curtime Redis启动完成" >> autostart.log;
else
echo "$curtime 系统检测到Redis运行正常" >> autostart.log;
fi
#检测Mongodb
checkRedis=`lsof -i:27017 |grep 'mongod' |grep -v grep |grep -v agent|sort | tail -1 | cut -f 1 -d ' '`
if [[ $checkRedis != 'mysqld' ]]; then
echo "$curtime 系统检测到Mongodb已挂掉,启动中...." >> autostart.log;
mongod --config /etc/mongod.conf #启动命令
echo "$curtime Mongodb启动完成" >> autostart.log;
else
echo "$curtime 系统检测到Mongodb运行正常" >> autostart.log;
fi
将脚本添加到定时任务
crontab -e
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root