會員註冊 / 登入  |  電腦版  |  Jump to bottom of page

Linux » [Linux]簡易網站發生故障通報程式

發表人: andowson, 七段學員
2008-02-17 18:20:31
最近客戶的網站當機了幾次, 由於客戶的網站用戶會打電話給他們申訴, 故客戶希望在障礙發生時系統可以發出一個通知, 至少一個email, 以便大家可以早點處理. 但是當機的系統自身都難保了, 怎麼還能發出email求救信?故我們可轉而採用由別的系統來監控該目標網站(TARGET), 透過wget這個指令可以抓取遠端網頁的功能, 進行HTTP連線測試, 如果無法成功抓首頁回來, 便判斷為網站連線失敗, 然後發信通知網站負責人(OWNER),底下是這個shell script的內容:
#! /bin/sh

# Name: webmon.sh
# Author: Andowson Chang (andowson [at] gmail [dot] com)
# Version: 0.2
# Created: 2008-02-16
# Last Modified: 2008-02-17
# Description: Web connection monitor (health check)
# If target web server failed, then notify its owner.
# Here email is used for the simplest and cheapest way.
# Usage: webmon.sh <hostname> <owner email>
# Example:
# 1. Single owner:
# /root/admin/webmon.sh www.yourcompany.com you@yourcompany.com
# 2.Multiple onwer:
# /root/admin/webmon.sh www.yourcompany.com you@yourcompany.com,yourboss@yourcompany.com
# 3. Set a cron job to keep checking a web site every few minutes.
# */5 * * * * root /root/admin/webmon.sh www.yourcompany.com you@yourcompany.com,yourboss@yourcompany.com
TARGET=$1
OWNER=$2
WEBMONLOG=/tmp/$TARGET.log
export LANG=en_US
wget -S -t 1 -T 5 http://$TARGET/ -O /tmp/index.html -o $WEBMONLOG
RESULT=`grep "HTTP/1." $WEBMONLOG | awk '{print $2}'`
TIMEOUT=`grep "timed out" $WEBMONLOG | wc -l`
if [ $TIMEOUT == 1 ] || [ ! $RESULT == 200 ]; then
mail -s "[ALERT]$TARGET HTTP connection fail" $OWNER < $WEBMONLOG
fi
# clean up
rm -rf /tmp/index.html
rm -rf $WEBMONLOG

這裡用到了wget的幾個參數, 主要是要取得HTTP的回應代碼, 並控制重試次數及連線的Timeout時間, 詳細說明如下
-S
--server-response
Print the headers sent by HTTP servers and responses sent by FTP servers.

-t number
--tries=number
Set number of retries to number. Specify 0 or inf for infinite retrying. The default is to retry 20 times, with the exception of fatal errors
like connection refused or not found (404), which are not retried.

-T seconds
--timeout=seconds
Set the network timeout to seconds seconds. This is equivalent to specifying --dns-timeout, --connect-timeout, and --read-timeout, all at the same time.
另外,這邊使用了export LANG=en_US來控制wget輸出訊息時的編碼為英文,以便配合cron使用.
使用時, 只需將webmon.sh放到/root/admin目錄下, 並更改權限為可執行, 然後在/etc/crontab中新增一行即可:
*/5 * * * * root /root/admin/webmon.sh www.yourcompany.com you@yourcompany.com,yourboss@yourcompany.com

檔案名稱 webmon.sh
描述 Website health monitor by shell script
檔案大小 1 Kbytes
下載次數 12 次
[Disk] 下載





會員註冊 / 登入  |  電腦版  |  Jump to top of page