shell之服務異常監測案例
例題一:web服務器nginx腳本服務監控
[root@oldboy43-01/server/scripts]#cat jiance_ng.sh
#!/bin/bash
if ! ss -lntup|grep [n]ginx &>/dev/null
then
/etc/init.d/nginx start
echo "nginx dead,but it‘s OK"|mail -s "whw11" [email protected]
fi
http_num=$(curl -I www.oldboyedu.com -s -w %{http_code} -o /dev/null)
if [ ${http_num} -ne 200 ];then
echo "nginx dead,but it‘s OK"|mail -s "whw11" [email protected]
fi
例題二:mysql服務器服務監控
[root@web03 scripts]# cat jiance_db.sh
#!/bin/bash
if ! ps -ef|grep [m]ysqld &>/dev/null
then
systemctl start mariadb.service &>/dev/null
echo "mysql dead,but it is OK"|mail -s "whw111" [email protected]
例題三:memcache緩存服務器監控
- [root@web03 scripts]# cat jiance_mem2.sh****
#!/bin/bash
port_status=$(ss -lntup|grep 11211|wc -l)
key1="oldboy0987"
printf "set key011 0 0 10\r\n${key1}\r\n"|nc 10.0.0.21 11211 &>/dev/null
key2=$(printf "get key011\r\n"|nc 10.0.0.21 11211|sed -n ‘2p‘|tr -d ‘\r‘)
if [ $port_status -eq 0 ];then
systemctl stop memcached.service
systemctl start memcached.service
if ! [ ${key1} == ${key2} ];then
systemctl restart memcached.service
echo "memcache dead,but it‘s OK"|mail -s "whw11" [email protected]
fi
fi
例題四:打印選擇菜單,按照選擇一鍵安裝不同的Web服務****
[root@oldboy43-01/server/scripts]#cat yijian.sh
#!/bin/bash
cat <<END
1.[install lamp]
2.[install lnmp]
3.exit
END
read -p "請輸入選項:" num
. /etc/init.d/functions
case $num in
1)
if [ -x /server/scripts/lamp.sh ];then
/server/scripts/lamp.sh
action "start installing lamp" /bin/true
action "lamp is installed" /bin/true
else
echo "一鍵腳本不存在或無執行權限"
fi
;;
2)
if [ -x /server/scripts/lnmp.sh ];then
/server/scripts/lnmp.sh
action "start installing lnmp" /bin/true
action "lnmp is installed" /bin/true
else
echo "一鍵腳本不存在或無執行權限"
fi
;;
3)
exit 3
;;
*)
echo "你的輸入有誤"
esac
例題五:Rsync啟動停止腳本
[root@oldboy43-01/server/scripts]#cat rsync_on.sh
#!/bin/bash
if ! [ -f /etc/rsyncd.conf ];then
echo "請先創建rsync配置文件"
exit 2
fi
read -p "請輸入要進行的操作:" cmd
. /etc/init.d/functions
case $cmd in
start)
if ss -lntup|grep rsync &>/dev/null;then
echo "rsync服務已啟動"
exit 2
else
rsync --daemon
action "rsync start" /bin/true
fi
;;
stop)
if ss -lntup|grep rsync &>/dev/null;then
killall rsync
sleep 3
action "rsync stop" /bin/true
else
echo "rsync是停止狀態"
fi
;;
restart)
if ss -lntup|grep rsync &>/dev/null;then
pkill -f rsync
rsync --daemon
action "rsync stop" /bin/true
action "rsync start" /bin/true
else
rsync --daemon
action "rsync stop" /bin/false
action "rsync start" /bin/true
fi
;;
*)
echo "輸入指令有誤:(start|stop|restart)"
esac
shell之服務異常監測案例