Linux下自动检测并恢复应用的shell脚本

本文讲述如在Linux系统中,如何通过检测应用端口(svcport)、执行文件(svcfile)或服务名称(svcname)的方式来判断应用运行状态,并且尝试(1次)自动恢复已经停止运行的应用。

编写脚本

vim /opt/auto_restart_app.sh

#!/bin/bash

# Define sleep time after restart application
slptime=5

# Define application information
appname=(httpd api)
svcport=(80 "")
svcfile=("" "api.jar")
svcname=("httpd" "")
pidfile=("" "")
exepath=("" "/opt/api/")
exemath=("systemctl start httpd" "java -jar api.jar")

# Define log path
logpath="/opt/scripts/log-"

# Defind how to check application status, do not need any edition
chkappstat () {
if [ -n "${svcport[$i]}" ];then
statchkmath="`netstat -tnlp | egrep -i tcp | awk {'print $4'} | awk -F':' '{if ($NF~/^[0-9]*$/) print $NF}' | egrep ${svcport[$i]}`"
elif [ -n "${svcfile[$i]}" ];then
statchkmath="`ps -ef | egrep ${svcfile[$i]} | grep -v grep`"
elif [ -n "${svcname[$i]}" ];then
osversion=`cat /etc/redhat-release | sed 's/[^0-9]//g'`
osversion=${osversion:0:1}
if [ "$osversion" -ge 7 ];then
statchkmath="`systemctl status ${svcname[$i]} | grep running`"
else
statchkmath="`service ${svcname[$i]} status | grep "is running"`"
fi
else
echo "ATTENTION! No math to check status of ${appname[$i]}" > $logpath${appname[$i]}
exit 0
fi
}

# Check pid file before restart application, do not need any edition
chkpidfile () {
if [ -e "${pidfile[$i]}" ];then
rm -f ${pidfile[$i]}
fi
}

# Check exe path before excuse exemath
startapp () {
if [ -d "${exepath[$i]}" ];then
cd ${exepath[$i]}
fi
${exemath[$i]}
}

# Start to check application status, do not need any edition
if [ ${#appname[@]} -eq 0 ];then
exit 0
fi
for ((i=0;i<${#appname[@]};i++));do
chkappstat
if [ -z "$statchkmath" ];then
chkpidfile
startapp
sleep $slptime
chkappstat
if [ -z "$statchkmath" ];then
echo "ERROR! ${appname[$i]} restart failed, please check its exemath" > $logpath${appname[$i]}
else
echo "WARNING! ${appname[$i]} restart manually at $(date "+%Y-%m-%d %H:%M:%S")" > $logpath${appname[$i]}
fi
else
echo "FINE! ${appname[$i]} status is fine at $(date "+%Y-%m-%d %H:%M:%S")" > $logpath${appname[$i]}
fi
done

添加定时任务

crontab -e

*/5 * * * * /opt/auto_restart_app.sh
赞 (0) 打赏

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

感谢您的支持与帮助

支付宝扫一扫打赏

微信扫一扫打赏