原文地址:http://www.oschina.net/question/12_45835
比较好的文章,分享下
需求列表:
crontab脚本如下:
*/5 * * * * root /home/username/sitemonitor.sh
sitemonitor.sh脚本如下:
#!/bin/bash # Simple HTTP/S availability notifications script v0.1 # March 20, 2012 by Jeff Rowberg - http://www.sectorfej.net HOSTS=( \ "http://www.yahoo.com" \ "https://www.google.com" \ "http://www.amazon.com" \ ) NOTIFY_FROM_EMAIL="Site Monitoring" NOTIFY_TO_EMAIL="Server Admin" STATUS_FILE="/home/username/sitemonitor.status" SLOW_THRESHOLD=10 OK_STATUSES=( "200" ) ################################################################ # NO MORE USERMOD STUFF BELOW THIS, MOST LIKELY # ################################################################ # thanks to stackoverflow! # stackoverflow.com/questions/3685970/bash-check-if-an-array-contains-a-value function contains() { local n=$# local value=${!n} for ((i=1; i < $#; i++)) { if [ "${!i}" == "${value}" ]; then echo "y" return 0 fi } echo "n" return 1 } rm -f /tmp/sitemonitor.status.tmp for HOST in "${HOSTS[@]}" do START=$(date +%s) RESPONSE=`wget $HOST --no-check-certificate -S -q -O - 2>&1 | \ awk '/^ HTTP/{print \$2}'` END=$(date +%s) DIFF=$(( $END - $START )) if [ -z "$RESPONSE" ]; then RESPONSE="0" fi if [ $(contains "${OK_STATUSES[@]}" "$RESPONSE") == "y" ]; then if [ "$DIFF" -lt "$SLOW_THRESHOLD" ]; then STATUS="UP" else STATUS="SLOW" fi else STATUS="DOWN" fi touch $STATUS_FILE STATUS_LINE=`grep $HOST $STATUS_FILE` STATUS_PARTS=($(echo $STATUS_LINE | tr " " "\n")) CHANGED=${STATUS_PARTS[2]} if [ "$STATUS" != "${STATUS_PARTS[5]}" ]; then if [ -z "${STATUS_PARTS[5]}" ]; then STATUS_PARTS[5]="No record" fi TIME=`date -d @$END` echo "Time: $TIME" > /tmp/sitemonitor.email.tmp echo "Host: $HOST" >> /tmp/sitemonitor.email.tmp echo "Status: $STATUS" >> /tmp/sitemonitor.email.tmp echo "Latency: $DIFF sec" >> /tmp/sitemonitor.email.tmp echo "Previous status: ${STATUS_PARTS[5]}" >> /tmp/sitemonitor.email.tmp if [ -z "${STATUS_PARTS[2]}" ]; then TIME="No record" else TIME=`date -d @${STATUS_PARTS[2]}` fi echo "Previous change: $TIME" >> /tmp/sitemonitor.email.tmp `mail -a "From: $NOTIFY_FROM_EMAIL" \ -s "SiteMonitor Notification: $HOST is $STATUS" \ "$NOTIFY_TO_EMAIL" < /tmp/sitemonitor.email.tmp` rm -f /tmp/sitemonitor.email.tmp #else # first report, but host is up, so no need to notify #fi CHANGED="$END" fi echo $HOST $RESPONSE $CHANGED $END $DIFF $STATUS >> /tmp/sitemonitor.status.tmp done mv /tmp/sitemonitor.status.tmp $STATUS_FILE