写了一个shell版mini监控脚本,纯属跟大家分享学习下,有兴趣学习shell的可以看下。(*_*)
总共3个脚本文件service.sh, daemon.sh ,tcp.sh
实现了一些基本功能:端口监控,存活监控,掉线邮件报警,重新上线邮件通知
将3个文件放在同个目录下
设置:在tcp.sh中可以设置邮件通知地址,与邮件通频率次数
运行: ./service.sh start
主要文件代码如下:
tcp.sh文件
#!/bin/bash LANG=C #邮件地址设置 fromaddress="[email protected]" #From地址 toaddress="[email protected]" #发送地址 ccaddress="[email protected]" #抄送地址 #邮件报警从复次数 remun=2 #被监控服务器、端口列表 server_all_list=(192.168.70.25:2004 192.168.70.24:80 192.168.16.56:80 ) ################################################################# #采用mail决定发送报警消息。 send_msg() { /bin/grep "$server_ip" mun.tmp > /dev/null 2>&1 if [ $? -eq 0 ] then mun=$(grep "$server_ip" mun.tmp | awk -F ‘:‘ ‘{print $2}‘) if [ $mun -lt $remun ];then echo "$messages" | mail -c $ccaddress -s "$server_ip is down" $toaddress -- -f $fromaddress newmun=$[$mun + 1] /bin/sed -i ‘s/‘$server_ip‘:‘$mun‘/‘$server_ip‘:‘$newmun‘/g‘ mun.tmp fi else echo "$server_ip:1" >> mun.tmp echo "$messages" | mail -c $ccaddress -s "$server_ip is down" $toaddress -- -f $fromaddress # echo "$messages" # echo "$server_ip" fi } #重置邮件已发送次数记录 reset_mun() { /bin/sed -i ‘/‘$server_ip‘/d‘ mun.tmp echo "server $server_ip online" | mail -c $ccaddress -s "$server_ip server online" $toaddress -- -f $fromaddress } ########### server_all_len=${#server_all_list[*]} i=0 while [ $i -lt $server_all_len ] do server_ip=$(echo ${server_all_list[$i]} | awk -F ‘:‘ ‘{print $1}‘) server_port=$(echo ${server_all_list[$i]} | awk -F ‘:‘ ‘{print $2}‘) #status: 0,http down 1,http ok 2,http down but ping ok if nc -vv -z -w 10 $server_ip $server_port > /dev/null 2>&1 then status=1 messages="server $server_ip,port $server_port can‘t access!" else if ping -c 1 $server_ip > /dev/null 2>&1 then status=2 messages="server $server_ip,Port $server_port cannot access,but Ping is connected!" else status=0 messages="server $server_ip,port $server_port and Ping cannot access!" fi fi if [ $status -eq 1 ];then grep "$server_ip" mun.tmp > /dev/null 2>&1 if [ $? -eq 0 ];then reset_mun fi else send_msg fi let i++ done
daemon.sh
#!/bin/sh dir=`pwd` while true do /bin/sh $dir/tcp.sh > /dev/null 2>&1 sleep 180 done
service.sh
#!/bin/sh dir=`pwd` start() { ps -ef |grep -v grep|grep daemon.sh > /dev/null 2>&1 if [ $? -eq 0 ];then exit else /usr/bin/nohup /bin/sh $dir/daemon.sh 2>&1 > /dev/null & fi } stop() { PID=$(ps -ef |grep -v grep|grep daemon.sh|awk ‘{print $2}‘) kill $PID } reload() { stop start } status() { ps -ef |grep -v grep|grep daemon.sh > /dev/null 2>&1 if [ $? -eq 0 ];then echo "daemon.sh is running..." else echo "daemon.sh is stop" fi } case "$1" in start) start && exit 0 $1 ;; stop) stop && exit 0 $1 ;; status) status && exit 0 $1 ;; reload) reload && exit 0 $1 ;; *) echo $"Usage: $0 {start|stop|status|reload}" exit 2 esac
时间: 2024-12-29 12:23:20