August 7Aug 7 I wanted to share a Bash script I use for my Unraid setup.I am using a portable power station (Oukitel P1500) as an offline UPS to back up my Unraid server, fiber ONT, ISP router, switch and mini PC's.Since power stations often lack a USB data connection to communicate with Unraid via NUT, this script monitors the power state by continuously pinging an IP address that relies on main grid power (such as your ISP router, a smart plug, or an external IP).Key Features:PID Locking (Prevent Duplicate Execution): Fixes a common issue with User Scripts where background processes stack up after array restarts or GUI triggers, preventing accidental/premature shutdowns.Accurate Failure Timer: Handles temporary network drops gracefully (e.g., during high network loads or Docker updates) without falsely triggering a shutdown.Timezone Fixed Logging: Logs events with exact local time (Europe/Amsterdam by default), making troubleshooting easy alongside Unraid WebGUI logs.SSD-Friendly Logging: Writes logs directly to an NVMe/SSD cache share (e.g., /mnt/user/temp/), keeping your array HDDs spun down and protecting the USB flash drive from wear.WebGUI Notifications: Triggers an official Unraid alert prior to initiating a graceful powerdown.The Script:#!/bin/bash# ==============================================================================# Unraid Ping Based Auto Shutdown Script for Non USB UPS / Power Stations# ==============================================================================# --- CONFIGURATION ---ROUTER_IP="192.168.2.254" # Target IP (Router, Smart Plug on grid, etc.)TIMEOUT_MINUTES=60 # Offline duration before shutdown (in minutes)PING_INTERVAL_SEC=10 # Interval between ping checks (in seconds)# Custom log file path (Recommended: an SSD cache share to prevent HDD spinup)LOG_FILE="/mnt/user/temp/ups_shutdown.log"LOCK_FILE="/var/run/ups_ping_shutdown.pid"# --- CALCULATIONS & VARIABLES ---OFFLINE_LIMIT_SEC=$((TIMEOUT_MINUTES * 60))ELAPSED_OFFLINE_SEC=0# Helper function with explicit timezone support for accurate timestampslog_message() {echo "$(TZ='Europe/Amsterdam' date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"}if [ -f "$LOCK_FILE" ]; thenPID=$(cat "$LOCK_FILE")if kill -0 "$PID" 2>/dev/null; thenlog_message "Script is already running (PID: $PID). Terminating this new instance."exit 1fifiecho $$ > "$LOCK_FILE"# Clean up lock file on exittrap 'rm -f "$LOCK_FILE"; exit' INT TERM EXITlog_message "UPS Monitor started. Target: $ROUTER_IP (Shutdown set after $TIMEOUT_MINUTES minutes offline)."while true; do# Ping target once with a 2-second timeoutif ping -c 1 -W 2 "$ROUTER_IP" &> /dev/null; then# Target responded -> Grid power is UPif [ $ELAPSED_OFFLINE_SEC -gt 0 ]; thenlog_message "Power/Connection restored! Timer reset from ${ELAPSED_OFFLINE_SEC}s back to 0s."ELAPSED_OFFLINE_SEC=0fielse# Target unreachable -> Grid power might be DOWNELAPSED_OFFLINE_SEC=$((ELAPSED_OFFLINE_SEC + PING_INTERVAL_SEC))MINUTES_OFFLINE=$((ELAPSED_OFFLINE_SEC / 60))# Log warnings every 60 seconds of downtime to avoid spamming the logif [ $((ELAPSED_OFFLINE_SEC % 60)) -eq 0 ]; thenlog_message "WARNING: Target ($ROUTER_IP) unreachable for ${MINUTES_OFFLINE} min (${ELAPSED_OFFLINE_SEC}/${OFFLINE_LIMIT_SEC} sec)."fi# Check if timeout threshold has been reachedif [ $ELAPSED_OFFLINE_SEC -ge $OFFLINE_LIMIT_SEC ]; thenlog_message "CRITICAL: Offline limit of $TIMEOUT_MINUTES minutes reached! Initiating clean Unraid shutdown."# Send Unraid WebGUI notification/usr/local/emhttp/webGui/scripts/notify -e "UPS Protection" -s "Power Outage Shutdown" -d "Target $TIMEOUT_MINUTES min unreachable. Shutting down Unraid server." -i "alert"# Remove lock file and trigger graceful shutdownrm -f "$LOCK_FILE"powerdownexit 0fifisleep $PING_INTERVAL_SECdoneHow to install:Install the User Scripts plugin from Community Applications.Add a new script named UPS_Ping_Shutdown.Paste the code above and adjust ROUTER_IP, TIMEOUT_MINUTES, and your timezone if needed.Set the schedule dropdown to At Startup of Array.Click Apply.Hope this helps anyone running power stations or off grid UPS units without USB monitoring! Feel free to ask if you have any questions or improvements. Edited August 8Aug 8 by RichyE
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.