首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Shell 腳本實戰:Linux 伺服器監控與網站可用性檢測自動化

     編輯:Java 相關知識

專案背景

雖然標題提到 Java 集合框架,但實際內容是兩個生產級 Shell 監控腳本,涵蓋系統資源監控與網站健康檢查,具備郵件告警、頻率控制、日誌記錄等完整功能。

腳本一:系統資源監控 (ServerMonitor.sh)

監控指標與閾值

  • CPU 使用率 > 90%
  • 記憶體可用 < 10%
  • Load Average (1分鐘) > 2

核心邏輯

#!/bin/bash
# 配置區
ROOT=$(cd "$(dirname "$0")"; pwd)
HOST=$(hostname)
NOTICE_EMAIL='admin@admin.com'
REMARK_EXPIRE=3600  # 告警間隔 1 小時

# 獲取 CPU 使用率 (vmstat 取樣 5 次平均)
GetCpu() {
    cpufree=$(vmstat 1 5 | sed -n '3,$p' | awk '{x+=$15} END {print x/5}' | awk -F. '{print $1}')
    cpuused=$((100 - cpufree))
    check_and_alert "CPU" "$cpuused" 90 "$CPU_REMARK"
}

# 獲取記憶體狀態
GetMem() {
    mem=$(free -m | sed -n '3,3p')
    used=$(echo $mem | awk '{print $3}')
    free=$(echo $mem | awk '{print $4}')
    total=$((used + free))
    limit=$((total / 10))  # 10% 閾值
    check_and_alert "Memory" "$free" "$limit" "$MEM_REMARK" "lt" # 可用小於閾值
}

# 獲取 Load Average
GetLoad() {
    load=$(uptime | awk -F 'load average: ' '{print $2}')
    m1=$(echo $load | awk -F ', ' '{print $1}' | awk -F. '{print $1}')
    check_and_alert "Load" "$m1" 2 "$LOAD_REMARK"
}

# 通用告警檢查 (支援大於/小於)
check_and_alert() {
    local metric=$1 current=$2 threshold=$3 remark_file=$4 op=${5:-gt}
    local remark=$(get_remark "$remark_file")
    if [ -z "$remark" ]; then
        if [ "$op" = "gt" ] && [ "$current" -gt "$threshold" ] || \
           [ "$op" = "lt" ] && [ "$current" -lt "$threshold" ]; then
            echo "Subject: ${HOST} ${metric} alert $(date)" | sendmail ${NOTICE_EMAIL}
            echo "$(date +%s)" > "$remark_file"
        fi
    fi
}

# 讀取上次告警時間,過期則清除
get_remark() { ... }

# 主流程
cpuinfo=$(GetCpu)
meminfo=$(GetMem)
loadinfo=$(GetLoad)
echo "cpu: ${cpuinfo}" >> "${CPU_LOG}"
echo "mem: ${meminfo}" >> "${MEM_LOG}"
echo "load: ${loadinfo}" >> "${LOAD_LOG}"

腳本二:網站可用性監控

檢測維度

  1. HTTP 狀態碼 = 200
  2. 總回應時間 < 10 秒

核心邏輯

SITES=("https://web01.example.com" "https://web02.example.com")
MAXLOADTIME=10
REMARKFILE='/tmp/monitor_load.remark'

for site in ${SITES[*]}; do
    # 獲取連線時間、傳輸時間、總時間
    site_load_time=$(curl -o /dev/null -s -w \
        "time_connect: %{time_connect}\ntime_starttransfer: %{time_starttransfer}\ntime_total: %{time_total}" \
        "${site}")
    site_access=$(curl -o /dev/null -s -w "%{http_code}" "${site}")
    time_total=${site_load_time##*:} # 提取總時間
    
    # 告警邏輯 (同樣 1 小時頻率控制)
    if [ -z "$REMARK" ]; then
        if [ "$time_total" = "0.000" ] || [ "$site_access" != "200" ]; then
            send_alert "${site} can not access"
        elif [ "${time_total%%.*}" -ge ${MAXLOADTIME} ]; then
            send_alert "${site} load time ${time_total}s"
        fi
    fi
done

部署與運維要點

現代化替代方案

雖然 Shell 腳本輕量、無依賴,但現代運維建議考慮:

  • Prometheus + Node Exporter + Alertmanager:業界標準監控棧
  • Zabbix / Datadog / Grafana Cloud:開箱即用的商業/開源方案
  • Telegraf + InfluxDB:輕量級時序資料庫方案

這兩個腳本展示了「用最簡單工具解決問題」的工程智慧,適合資源受限環境或作為學習系統監控原理的教材。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
項目建議
排程crontab -e 添加 */1 * * * * /path/ServerMonitor.sh (每分鐘) 或 */30 * * * * * (每30秒需 systemd timer)
郵件服務確保 sendmail 或 postfix 已配置可發送外部郵件
日誌輪轉配置 logrotate 避免日誌佔滿磁碟
權限腳本需 chmod +x,以監控用戶身分執行
擴展可加入磁碟空間、TCP 連線數、業務指標等監控項