監控程式和埠,然後在掛了的時候重新啓動

2020-08-09 22:17:04

監控某個程式,以nginx爲例:

a=1
while ((a<2))
do
nginx_process_num=$(ps -ef | grep nginx | grep -v grep | wc -l)
# 判斷進程是否存在,不存在就啓動Nginx
if [ $nginx_process_num  -eq 0 ]; then
    cd /usr/local/nginx/sbin/
    ./nginx -c /usr/local/nginx/conf/nginx.conf
echo "$(date +%Y%m%d-%H%M)重新啓動了"
else
echo "$(date +%Y%m%d-%H%M)狀態正常"
fi
sleep 1m
done
 

 

監控某個埠:以8888爲例

a=1
while ((a<2))
do
process_num=$(netstat -an | grep ":8888" | awk '$1 == "tcp" && $NF == "LISTEN" {print $0}' | wc -l)
# 判斷進程是否存在,不存在就啓動Nginx
if [ $process_num  -eq 0 ]; then
    cd /root
    ./reloadScg.sh
echo "$(date +%Y%m%d-%H%M)重新啓動了"
else
echo "$(date +%Y%m%d-%H%M)正常執行"
fi
sleep 2m
done
 

 

 

常用幾個命令:

看nginx是否存活:ps -ef | grep nginx | grep -v grep | wc -l
後臺啓動:nohup sh /monitor/monitorNginx.sh >/monitor/ng.out 2>&1 &
看啓動的指令碼進程:ps -aux | grep "monitorNginx.sh"

判斷埠是否存活:netstat -an | grep ":8888" | awk '$1 == "tcp" && $NF == "LISTEN" {print $0}' | wc -l

開機自啓動:vi /etc/rc.d/rc.local
加入:nohup sh /monitor/monitorNginx.sh >/monitor/ng.out 2>&1 &