linux脚本监控nginx服务并设置自动启动
一、 编写脚本nginx_check.sh
-
本次nginx通过源代码编译安装,nginx运行程序所在位置为:/usr/local/nginx/sbin/nginx
-
nginx使用的端口是8080,通过判断端口8080是否存在,从而判断nginx是否正常运行,如果服务停止,则启动nginx
-
脚本所在目录:/etc/nginx
-
日志所在目录:/etc/nginx/nginx.check.logs/
-
编写脚本:vim nginx_check.sh,脚本内容如下:
vim nginx_check.sh
#!/bin/bash date=`date +%Y-%m-%d` date_time=`date +%Y-%m-%d_%H:%M:%S` logs_back=/etc/nginx/nginx.check.logs logs_file=$logs_back/$date.nginx.check.logs mkdir -p /etc/nginx/nginx.check.logs touch $logs_file nginx_port=`netstat -nlt |grep 8080 |awk '{print $4}'| cut -d : -f 2` echo "" >> $logs_file echo "------------------Time Now: $date_time--------------------" >> $logs_file echo "nginx_port:$nginx_port" >> $logs_file if [ "$nginx_port" = "8080" ];then echo "------------------Time Now: $date_time--------------------" >> $logs_file echo "------------------ps -ef |grep nginx --------------------" >> $logs_file ps -ef |grep nginx >> $logs_file echo "------------------result------------------" >> $logs_file echo 'nginx server is running!!' >> $logs_file echo "------------------result------------------" >> $logs_file else echo "------------------Time Now: $date_time--------------------" >> $logs_file echo "------------------result------------------" >> $logs_file echo 'Nginx server is stopped!!' >> $logs_file echo "------------------result------------------" >> $logs_file echo '------------------start nginx : /usr/local/nginx/sbin/nginx------------------' >> $logs_file /usr/local/nginx/sbin/nginx >> $logs_file nginx_start_port=`netstat -nlt |grep 8080 |awk '{print $4}'| cut -d : -f 2` echo "nginx_start_port:$nginx_start_port" >> $logs_file if [ "$nginx_start_port"="8080" ];then echo "------------------Time Now: $date_time--------------------" >> $logs_file echo "------------------ps -ef |grep nginx --------------------" >> $logs_file ps -ef |grep nginx >> $logs_file echo "------------------result------------------" >> $logs_file echo 'Nginx service started Successfully!' >> $logs_file echo "------------------result------------------" >> $logs_file else echo "------------------Time Now: $date_time--------------------" >> $logs_file echo "------------------result------------------" >> $logs_file echo 'Nginx service started Failed!' >> $logs_file echo "------------------result------------------" >> $logs_file fi fi
-
设置脚本权限:chmod 777 nginx_check.sh
chmod 777 nginx_check.sh
二、设置定时任务
- 使用crontab定时任务,使用root用户,编写定时任务,该任务每隔两分钟执行一次
crontab -e
- 添加内容
*/2 * * * * sh /etc/nginx/nginx_check.sh
- 查看日志:
重启nginx服务器日志:cat nginx.check.logs/2020-06-10.nginx.check.logs
nginx服务运行中日志:
- 使用crontab定时任务,使用root用户,编写定时任务,该任务每隔两分钟执行一次