先安装必要包
yum -y install nc mail
shell代码(注意,一定要在VIM中编辑,否则执行会有问题)
port=$1
if [ ! -n "$port" ];then
echo "please enter the args port!"
exit
fi
service_name=$2
nc -w2 localhost $port
if [ $? != 0 ];then
echo '【'`date +"%Y-%m-%d %H:%M:%S"`'】检测到端口【'${port}'】已经关闭,该服务重新启动'>>/root/monitor_log.log
eval $2
exit
fi
添加邮件功能
若想使用shell中的第14行代码,需要事先安装邮件服务。安装步骤如下:
vim /etc/mail.rc
在最后添加以下两行代码
set from=xxx@xxx.com smtp=mail.xxx.com
set smtp-auth-user=xxx@xxx.com smtp-auth-password=123456 smtp-auth=login
发送邮件命令,添加到第14行(shell)
echo "the port ${port} is down,the server is restart ${port} port!!"|mail -s "port ${port}/${service_name} is down!" xxx@xxx.com
最终代码(shell)
vim /root/port_monitor.sh
chmod +x /root/port_monitor.sh
port=$1
if [ ! -n "$port" ];then
echo "please enter the args port!"
exit
fi
service_name=$2
nc -w2 localhost $port
if [ $? != 0 ];then
echo '【'`date +"%Y-%m-%d %H:%M:%S"`'】检测到端口【'${port}'】已经关闭,该服务重新启动'>>/root/monitor_log.log
if [ -n "$service_name" ];then
eval $2
fi
if [ ! -n "$service_name" ];then
mkdir /tmp/portmonitor/ -p
touch /tmp/portmonitor/${port}.log
flag=$(cat /tmp/portmonitor/${port}.log)
if [ ! -n "$flag" ] || [ "1" != "$flag" ];then
echo '1'>/tmp/portmonitor/${port}.log
fi
fi
echo "the port ${port} is down,the server is restart ${port} port!!"|mail -s "port ${port}/${service_name} is down!" xxx@xxx.com
exit
fi
执行定时任务 每十秒执行一次
crontab -e
* * * * * sleep 10; /root/port_monitor.sh 80 "/etc/init.d/nginx start"
* * * * * sleep 20; /root/port_monitor.sh 80 "/etc/init.d/nginx start"
* * * * * sleep 30; /root/port_monitor.sh 80 "/etc/init.d/nginx start"
* * * * * sleep 40; /root/port_monitor.sh 80 "/etc/init.d/nginx start"
* * * * * sleep 50; /root/port_monitor.sh 80 "/etc/init.d/nginx start"