読者です 読者をやめる 読者になる 読者になる

サービス監視用スクリプト(bash,やっつけ)

やっつけなので注意☆

基本的な考え方

  • 監視スクリプト本体 : check-XXXX.sh
  • 監視対象のリストファイル : list-XXX.txt
  • 監視スクリプトから利用されるコマンドファイル : cmd-XXXX.txt
  • 動作ディレクトリ : /usr/local/tools/monitor
  • ログ保存ディレクトリ : /usr/local/tools/monitor/logs
  • テンポラリファイル : /tmp/XXXX-ng.txt

想定環境

CentOS6系

check ping

check-ping.sh

#!/bin/bash
#
# check ping script. 
# ver 0.1 2016/05/28
#
export LANG=C
CHECK=ping
DIR=/usr/local/tools/monitor
LOG=/usr/local/tools/monitor/logs/${CHECL}.log
LIST=/usr/local/tools/monitor/list-${CHECK}.txt
TEMP=/tmp/ping-ng.txt
MAIL_TO=user1@sXX.hogehoge.local

cat ${LIST}| while read DEST
  do
    ping -c 2 -w 2 ${DEST} > /dev/null
    if [ $? == 0 ] ;
    then
      echo `date +%F' '%X` "${DEST} ${CHECK} : OK" >> ${LOG}
    else
      echo `date +%F' '%X` "${DEST} ${CHECK} : NG" >  ${TEMP}
      cat ${TEMP}                         >> ${LOG}
      cat ${TEMP} | mail -s "alert [${DEST}] ${CHECK} NG!" ${MAIL_TO}
    fi
  done

list-ping.txt

192.168.1.1
192.168.1.2
192.168.1.3

check web

check-web.sh

#!/bin/bash
#
# check web script.
# ver 0.1 2016/05/28
export LANG=C
CHECK=web
#PORT=80
DIR=/usr/local/tools/monitor
LOG=${DIR}/logs/${CHECK}.log
LIST=${DIR}/list-${CHECK}.txt
REMOTE_CMD=${DIR}/cmd-${CHECK}.txt
TEMP=/tmp/${CHECK}-ng.txt

MAIL_TO=user1@sXX.hogehoge.local

cat ${LIST}| while read DEST
  do
    SITE=`echo ${DEST}| awk -F"/" '{print $3}'`
    curl -f ${DEST} > /dev/null 2>&1
    if [ $? == 0 ] ;
    then
      echo `date +%F' '%X` "${DEST} ${CHECK} : OK" >> ${LOG}
    else
      echo `date +%F' '%X` "${DEST} ${CHECK} : NG" >  ${TEMP}
      cat ${TEMP}                                  >> ${LOG}
      cat ${TEMP} | mail -s "alert [${SITE}] ${CHECK} NG!" ${MAIL_TO}
    fi
  done

list-web.txt

http://www1.sXX.hogehoge.local/
http://www2.sXX.hogehoge.local/

check smtp

check-smtp.sh

#!/bin/bash +x

# check smtp script.
# ver 0.1 2016/05/28
export LANG=C
CHECK=smtp
PORT=25
DIR=/usr/local/tools/monitor
LOG=${DIR}/logs/${CHECK}.log
LIST=${DIR}/list-${CHECK}.txt
REMOTE_CMD=${DIR}/cmd-${CHECK}.txt
TEMP=/tmp/${CHECK}-ng.txt
RESULT="221 2.0.0 Bye"

MAIL_TO=user1@sXX.hogehoge.local

cat ${LIST}| while read DEST
  do
    cat ${REMOTE_CMD} | nc ${DEST} ${PORT} | tail -1 | grep "${RESULT}" > /dev/null 2>&1
    if [ $? == 0 ] ;
    then
      echo `date +%F' '%X` "${DEST} ${CHECK} : OK" >> ${LOG}
    else
      echo `date +%F' '%X` "${DEST} ${CHECK} : NG" >  ${TEMP}
      cat ${TEMP}                                  >> ${LOG}
      cat ${TEMP} | mail -s "alert [${DEST}] ${CHECK} NG!" ${MAIL_TO}
    fi
  done

list-smtp.txt

192.168.1.3

cmd-smtp.txt

ehlo test
quit