Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Shell 腳本判斷服務是否運行並自動拉起(pgrep 實戰)

編輯:Linux 教學

核心邏輯

使用 pgrep 依進程名稱獲取 PID,若存在則服務運行;否則啟動服務。

通用檢測腳本

#!/bin/bash
# check_service.sh
# 用法:./check_service.sh <服務名>
# 服務名需與進程名稱一致,或自行修改啟動指令

SERVICE=$1
if [ -z "$SERVICE" ]; then
    echo "用法: $0 <服務名>"
    exit 1
fi

PIDS=$(pgrep -x "$SERVICE")
if [ -n "$PIDS" ]; then
    echo "[$(date '+%F %T')] $SERVICE 正在運行 (PID: $PIDS)"
else
    echo "[$(date '+%F %T')] $SERVICE 未運行,嘗試啟動..."
    /sbin/service "$SERVICE" start
    sleep 2
    if pgrep -x "$SERVICE" >/dev/null; then
        echo "[$(date '+%F %T')] $SERVICE 啟動成功"
    else
        echo "[$(date '+%F %T')] $SERVICE 啟動失敗,請人工介入" >&2
        exit 1
    fi
fi

進階:支援 systemd、自定義啟動指令、日誌輪轉

#!/bin/bash
# monitor_service.sh
# 配置檔:/etc/monitor_service.conf
# 格式:服務名|檢測模式(pgrep|systemd)|啟動指令|檢測間隔秒

CONF=${1:-/etc/monitor_service.conf}
LOG=/var/log/monitor_service.log

[ -f "$CONF" ] || { echo "配置檔 $CONF 不存在"; exit 1; }

while IFS='|' read -r name mode cmd interval; do
    # 跳過註釋與空行
    [[ "$name" =~ ^#.*$ ]] && continue
    [ -z "$name" ] && continue

    interval=${interval:-60}
    running=0

    case "$mode" in
        pgrep)
            pgrep -x "$name" >/dev/null && running=1
            ;;
        systemd)
            systemctl is-active --quiet "$name" && running=1
            ;;
        *)
            echo "[$(date)] 未知模式 $mode,跳過 $name" | tee -a "$LOG"
            continue
            ;;
    esac

    if [ $running -eq 1 ]; then
        echo "[$(date)] $name 運行正常" >> "$LOG"
    else
        echo "[$(date)] $name 停止,執行啟動: $cmd" | tee -a "$LOG"
        eval "$cmd"
        sleep 3
        # 再次檢測
        case "$mode" in
            pgrep) pgrep -x "$name" >/dev/null && echo "[$(date)] $name 啟動成功" >> "$LOG" || echo "[$(date)] $name 啟動失敗" | tee -a "$LOG" ;;
            systemd) systemctl is-active --quiet "$name" && echo "[$(date)] $name 啟動成功" >> "$LOG" || echo "[$(date)] $name 啟動失敗" | tee -a "$LOG" ;;
        esac
    fi
done < "$CONF"

配置檔範例(/etc/monitor_service.conf)

# 服務名|模式|啟動指令|間隔(秒)
nginx|pgrep|/sbin/service nginx start|60
mysqld|systemd|systemctl start mysqld|60
php-fpm|systemd|systemctl start php-fpm|60
redis|pgrep|/usr/local/bin/redis-server /etc/redis.conf|30

部署為 systemd 定時器(替代 crontab)

# /etc/systemd/system/monitor-service.service
[Unit]
Description=Monitor Critical Services
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/monitor_service.sh
StandardOutput=append:/var/log/monitor_service.log
StandardError=append:/var/log/monitor_service.log

# /etc/systemd/system/monitor-service.timer
[Unit]
Description=Run monitor-service every minute

[Timer]
OnBootSec=1min
OnUnitActiveSec=1min
Persistent=true

[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable --now monitor-service.timer

總結

從簡單的 pgrep 單行檢測,到支援 systemd、配置化、systemd timer 定時拉起的完整監控體系,根據業務規模選擇適當層級。核心原則:**檢測與啟動分離、冪等啟動、日誌留痕、失敗告警**。

Copyright © Windows教程網 All Rights Reserved