Script to auto restart openvpn service

#!/bin/sh
IP=8.8.8.8  # Address to ping
PF=5        # Number of consecutive ping failures before restarting the service
COUNTERFILE=/tmp/counter.txt

sleep 180   #Initial delay

while true; do

if ! ping -c 1 -W 1 $IP >/dev/null; then
        if [ -f "$COUNTERFILE" ]; then
         counter=$(cat $COUNTERFILE)
        else
         counter="0"
        fi
        if [ "$counter" -ge "$PF" ]; then
         /etc/init.d/openvpn restart
         echo "0" > "$COUNTERFILE"
        else
         let "counter+=1"
         echo "$counter" > "$COUNTERFILE"
        fi
else
 echo "0" > "$COUNTERFILE"
fi
sleep 5
done
2 Likes