Skip to content

Instantly share code, notes, and snippets.

@DarrenKwonDev
Last active July 22, 2025 00:11
Show Gist options
  • Save DarrenKwonDev/0074d5eab5cb7416e368f1b3e0fc84af to your computer and use it in GitHub Desktop.
Save DarrenKwonDev/0074d5eab5cb7416e368f1b3e0fc84af to your computer and use it in GitHub Desktop.
#!/bin/bash
# --------------------
# register this script in cronjob
# --------------------
TARGET_IP="" # fill this
PING_TIMEOUT=10
LOG_FILE="/var/log/ts_monitor.log"
CNT_FILE="/tmp/ts_fail_cnt"
FAIL_THRESHOLD=3
log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
ping_test() {
ping -c 1 -W "$PING_TIMEOUT" "$TARGET_IP" > /dev/null 2>&1
return $?
}
ts_restart() {
log_message "tailscale restart"
tailscale down
sleep 2
tailscale up
if [ $? -eq 0 ]; then
log_message "tailscale restart done"
else
log_message "tailscale restart faile with $?"
fi
}
fail_count=$(cat "$CNT_FILE" 2>/dev/null || echo "0")
if ping_test; then
log_message "ping test successful"
if [ $fail_count -gt 0 ]; then
log_message "connection recovered (fail count: $fail_count -> 0)"
echo "0" > "$CNT_FILE"
fi
else
fail_count=$((fail_count + 1))
echo "$fail_count" > "$CNT_FILE"
log_message "ping failed ($fail_count/$FAIL_THRESHOLD) - $TARGET_IP"
if [ $fail_count -ge $FAIL_THRESHOLD ]; then
log_message "threshold reached! starting recovery process..."
ts_status=$(tailscale status | grep "$TARGET_IP")
log_message "current tailscale status: $ts_status"
ts_restart
sleep 5
if ping_test; then
log_message "recovery successful!"
echo "0" > "$CNT_FILE"
else
log_message "WARNING: connection still failed after restart"
fi
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment