Skip to content

Instantly share code, notes, and snippets.

@xmesaj2
Created March 4, 2025 22:37
Show Gist options
  • Save xmesaj2/701b2ace833fc86df0300c9fbf2865e0 to your computer and use it in GitHub Desktop.
Save xmesaj2/701b2ace833fc86df0300c9fbf2865e0 to your computer and use it in GitHub Desktop.
/etc/init.d/ipsec-watchdog.sh ipfire restart ipsec connection (with help of grok ai)
#!/bin/bash
# IPSec watchdog for OracleVPSTunnel
# chkconfig: 2345 90 10
CONNECTION_NAME="VPSToHomeTunnel"
LOG_FILE="/var/log/ipsec-watchdog.log"
PID_FILE="/var/run/ipsec-watchdog.pid"
MAX_RETRIES=3
get_tunnel_status() {
/usr/sbin/ipsec status | grep -q ESTABLISHED
return $?
}
restart_ipsec() {
echo "$(date): Restarting IPSec connection" >> $LOG_FILE
/usr/sbin/ipsec down $CONNECTION_NAME
sleep 2
/usr/sbin/ipsec up $CONNECTION_NAME
}
start_watchdog() {
echo "$(date): Starting watchdog for $CONNECTION_NAME" >> $LOG_FILE
local retries=0
while true; do
if ! get_tunnel_status; then
echo "$(date): Tunnel down! (Attempt $((retries+1))/$MAX_RETRIES)" >> $LOG_FILE
if [ $retries -lt $MAX_RETRIES ]; then
restart_ipsec
((retries++))
sleep 30
else
echo "$(date): Max retries reached. Waiting 5 minutes..." >> $LOG_FILE
retries=0
sleep 300
fi
else
retries=0
sleep 60
fi
done
}
is_running() {
if [ -f "$PID_FILE" ]; then
local pid=$(cat "$PID_FILE" 2>/dev/null)
if [ -n "$pid" ] && ps -p "$pid" > /dev/null 2>&1; then
return 0 # Process is running
else
rm -f "$PID_FILE" # Clean up stale PID file
return 1 # Process is not running
fi
fi
return 1 # No PID file exists
}
case "$1" in
start)
if is_running; then
echo "Watchdog is already running"
exit 1
fi
start_watchdog &
echo $! > "$PID_FILE"
echo "$(date): Started watchdog (PID $!)" >> $LOG_FILE
;;
stop)
if is_running; then
PID=$(cat "$PID_FILE" 2>/dev/null)
if [ -n "$PID" ]; then
echo "$(date): Attempting to stop watchdog (PID $PID)" >> $LOG_FILE
kill "$PID" 2>/dev/null
sleep 1
if ps -p "$PID" > /dev/null 2>&1; then
echo "$(date): Process still running, forcing termination" >> $LOG_FILE
kill -9 "$PID" 2>/dev/null
sleep 1
if ps -p "$PID" > /dev/null 2>&1; then
echo "$(date): Failed to stop watchdog (PID $PID)" >> $LOG_FILE
else
echo "$(date): Successfully force-stopped watchdog (PID $PID)" >> $LOG_FILE
fi
else
echo "$(date): Successfully stopped watchdog (PID $PID)" >> $LOG_FILE
fi
rm -f "$PID_FILE"
else
echo "$(date): PID file empty or corrupt" >> $LOG_FILE
fi
else
echo "$(date): Watchdog is not running" >> $LOG_FILE
echo "Watchdog is not running"
fi
;;
restart)
$0 stop
$0 start
;;
status)
if get_tunnel_status; then
echo "Tunnel $CONNECTION_NAME: UP"
else
echo "Tunnel $CONNECTION_NAME: DOWN"
fi
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
;;
esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment