Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

實作 Apache 服務監控腳本:掛掉自動重啟並記錄時間與次數

網站服務最怕的不是當機,而是當機沒人發現。寫一個常駐的小腳本持續探測,異常就重啟並留下記錄,是最基本的自癒手段。

第一版:最簡骨架

#!/bin/bash
while [ 1 ]
do
    wget https://127.0.0.1/a.html > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        service apache restart >/dev/null 2>&1
    else
        wt=`cat a.html`
        if [ $wt != 'OK' ]
        then
            service apache restart > /dev/null 2>&1
        fi
    fi
    sleep 2
done

它做兩層判斷:先確認能不能連上(wget 的返回碼),能連上再檢查回應內容是否為 OK。之所以要兩層,是因為「連得上但回 500」這種假活著的狀態,只看端口是發現不了的。探測用的 /www/a.html 內容就是一行 OK。

實測結果

[root@localhost ~]# lsof -i:80
COMMAND  PID   USER  FD  TYPE DEVICE SIZE NODE NAME
httpd   32105 root   3u  IPv4 409340    TCP *:http (LISTEN)
httpd   32109 daemon 3u  IPv4 409340    TCP *:http (LISTEN)
...
[root@localhost ~]# killall httpd
[root@localhost ~]# lsof -i:80      # 短暫空窗
[root@localhost ~]# lsof -i:80
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
httpd   618 root  3u IPv4 411612    TCP *:http (LISTEN)
httpd   623 daemon 3u IPv4 411612   TCP *:http (LISTEN)

殺掉 httpd 後大約一兩秒的空窗,之後服務就回來了。若生產環境對空窗敏感,可以把 sleep 改成 1。

踩到的坑:wget 產生的檔案會爆量

跑一陣子後會發現目錄裡堆出一堆 a.html.176、a.html.177……原來 wget 遇到同名檔會自動加序號續存。修法很簡單,在迴圈結尾把檔案 redistribute 掉:

rm -rf a.html

第二版:加入重啟記錄

#!/bin/bash
while [ 1 ]
do
    wget https://127.0.0.1/a.html > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        service apache restart >/dev/null 2>&1
        echo "apache restart at `date +%y-%m-%d\ %H:%M:%S`" >> times.txt
    else
        wt=`cat a.html`
        if [ $wt != 'OK' ]
        then
            service apache restart > /dev/null 2>&1
            echo "apache restart at `date +%y-%m-%d\ %H:%M:%S`" >> times.txt
        fi
    fi
    rm -rf a.html
    sleep 2
done

測試時用 killall httpd 觸發一次,times.txt 就多一行;把 a.html 內容改成非 OK,可以看到每兩秒重啟一次並持續寫入:

[root@localhost shell]# tail -f times.txt
apache restart at 13-10-15 17:47:27
apache restart at 13-10-15 17:47:40
apache restart at 13-10-15 17:48:18
apache restart at 13-10-15 17:48:20
...

改回 OK 之後日誌停止。想知道總共重啟幾次:

wc -l times.txt | cut -d" " -f1

順手練手的兩個小腳本

用雙層迴圈印出直角三角形:

#!/bin/bash
a=1; b=5
while [ $a -le $b ]
do
    c=1
    while [ $c -le $a ]
    do
        echo -n \*
        let c++
    done
    let a++
    echo
done
# 輸出:
# *
# **
# ***
# ****
# *****

可以再加強的地方

這個腳本還很粗糙,正式上線前建議補上:改用 while true 並搭配 systemd 或 supervisor 讓它開機自啟並自動重拉;用 curl -f 取代 wget 避免殘留檔案;加入連續失敗次數門檻,避免服務一有抖動就被瘋狂重啟(上面 17:48 那段每兩秒重啟的紀錄就是反面教材);以及重啟後送出通知,否則日誌寫得再漂亮也沒人看。

Copyright © Linux教程網 All Rights Reserved