Skip to content

Instantly share code, notes, and snippets.

@disafronov
Last active October 3, 2025 09:46
Show Gist options
  • Select an option

  • Save disafronov/2849b3ee8aeae1626f35ecb0165785d7 to your computer and use it in GitHub Desktop.

Select an option

Save disafronov/2849b3ee8aeae1626f35ecb0165785d7 to your computer and use it in GitHub Desktop.

Revisions

  1. disafronov revised this gist Oct 3, 2025. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion server-monitor.sh
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@
    IP="192.168.2.2" # server IP
    MAC="50:EB:F6:50:3E:AE" # MAC address for WOL
    INTERFACE="br-lan" # network interface for ping/etherwake
    INTERFACE_RESTART="lan1@eth0" # interface to restart
    INTERFACE_RESTART="lan1" # interface to restart
    MAX_FAILS=4 # 4 * 5 min = 20 min
    STATE="/tmp/server-monitor.state" # temp file for fail counter
    LOG_TAG="server-monitor" # logger tag
  2. disafronov created this gist Oct 3, 2025.
    62 changes: 62 additions & 0 deletions server-monitor.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    #!/bin/sh

    IP="192.168.2.2" # server IP
    MAC="50:EB:F6:50:3E:AE" # MAC address for WOL
    INTERFACE="br-lan" # network interface for ping/etherwake
    INTERFACE_RESTART="lan1@eth0" # interface to restart
    MAX_FAILS=4 # 4 * 5 min = 20 min
    STATE="/tmp/server-monitor.state" # temp file for fail counter
    LOG_TAG="server-monitor" # logger tag

    # function to log messages
    log() {
    logger -t "$LOG_TAG" -- "$1"
    }

    # function to check host availability
    check_host() {
    log "Checking host $IP via interface $INTERFACE (fail count: $FAILS)"
    if ping -c1 -W1 -I "$INTERFACE" "$IP" >/dev/null 2>&1; then
    echo 0 > "$STATE"
    log "Host $IP is up"
    exit 0
    else
    log "Host $IP is not responding (fail count: $FAILS)"
    fi
    }

    # read current fail count or 0
    [ -f "$STATE" ] && FAILS=$(cat "$STATE") || FAILS=0

    # check if interface exists
    if ! ip link show "$INTERFACE" >/dev/null 2>&1; then
    log "Interface $INTERFACE not found, cannot ping host"
    exit 1
    fi

    # ping host
    check_host

    # restart interface
    if ip link show "$INTERFACE_RESTART" >/dev/null 2>&1; then
    log "Restarting interface $INTERFACE_RESTART"
    ip link set "$INTERFACE_RESTART" down
    sleep 1
    ip link set "$INTERFACE_RESTART" up
    sleep 2
    log "Interface $INTERFACE_RESTART was restarted"

    # check host again after interface restart
    check_host
    else
    log "Interface $INTERFACE_RESTART not found, skipping restart"
    fi

    FAILS=$((FAILS+1))
    echo $FAILS > "$STATE"

    # send WOL if needed
    if [ "$FAILS" -ge "$MAX_FAILS" ]; then
    log "Host $IP has been down for too long, sending WOL packet"
    etherwake -i "$INTERFACE" "$MAC"
    fi