一、nginx监听并自动重启Shell脚本
vim /usr/local/nginx/sbin/nginx_restart.sh
nginx_restart.sh
#!/bin/bash
#Monitor nginx service
#check root user
if [ $(id -u) != "0" ]
then
echo "Not the root user! Try using sudo command!"
exit 1
fi
netstat -anop | grep 0.0.0.0:443
if [ $? -ne 1 ]
then
exit
fi
echo $(date +%T%n%F)" Restart nginx Services " >> /usr/local/nginx/logs/nginx.log 2>&1
#/usr/local/nginx/sbin/nginx -s quit
/usr/local/nginx/sbin/nginx
其实主要内容就是
检查是否是root用户
检查监听服务程序的端口是否还正常
对运行不正常的进程进行重启
授权脚本
:wq! 保存退出
chmod +w nginx_restart.sh 授权为可自行脚本
加入Linux crontab自动任务
sudo crontab -e
*/1 * * * * sh /usr/local/nginx/sbin/nginx_restart.sh
二、nginx监听运行状态shell脚本
#!/bin/sh
MONITOR_LOG=/usr/local/nginx/logs/nginx_monitor.log
nginx_monitor()
{
#nginx的端口号
PORT="443"
#获取nginx端口监听状态,如果nginx正常运行,PORT_FLAG值为0
PORT_STATUS=$(netstat -plnt|grep $1|grep ${PORT})
#获取上一个命令的退出状态,正常退出为0
PORT_FLAG=$?
#使用管道命令查询nginx的进程号
NGINX_STATUS=$(ps -ef |grep $1|grep -v 'grep'|grep master|awk '{print $2}')
#如果进程号存在并且端口监听正常,则说明nginx正常运行
if [ ${NGINX_STATUS} ] && [ ${PORT_FLAG} = "0" ];then
echo `date "+%Y/%m/%d %H:%M:%S $1 is running"` >>${MONITOR_LOG} 2>&1
else
echo `date "+%Y/%m/%d %H:%M:%S [error] $1 has already shutdown"` >>${MONITOR_LOG} 2>&1
fi
}
#调用nginx_monitor函数,其中nginx是参数,为nginx的进程名,也就是nginx的目录名
nginx_monitor nginx
手动执行脚本使用如下命令
sudo bash nginx_monitor.sh
#或者
sudo sh nginx_monitor.sh #需要先获得执行权限
定时执行,需要使用linux的crontab,使用 sudo crontab -e 命令打开配置文件
*/1 * * * * sh /usr/local/nginx/sbin/nginx_monitor.sh