使用 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
#!/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"
# 服務名|模式|啟動指令|間隔(秒)
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
# /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 定時拉起的完整監控體系,根據業務規模選擇適當層級。核心原則:**檢測與啟動分離、冪等啟動、日誌留痕、失敗告警**。
VMware Workstation 共享資料夾設定:Host (Windows) ↔ Guest (Linux) 免網路檔案傳輸
Linux 下 Oracle DBCA 創建數據庫報錯「Xlib: connection refused」解決:X11 轉發與顯示授權
Windows 7 與 Fedora 雙系統安裝:保護 MBR、使用 EasyBCD 管理開機選單完整教學
Linux 版 QQ 安裝與卸載完整指南 (RPM/DEB/TAR.GZ)
Fedora 8 / RHEL 系列系統安裝與配置 JDK 6.0 完整教學