eibgrad

merlin-ovpn-watchdog-74660.sh

Sep 25th, 2021 (edited)
1,600
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/sh
  2. # version: 2.1.0, 03-dec-2021, by eibgrad
  3. # href: https://tinyurl.com/2p9a68ne
  4.  
  5. SCRIPTS_DIR='/jffs/scripts'
  6. SCRIPT="$SCRIPTS_DIR/services-start"
  7.  
  8. mkdir -p $SCRIPTS_DIR
  9.  
  10. create_script() {
  11. cat << "EOF" > $SCRIPT
  12. #!/bin/sh
  13. set -x # uncomment/comment to enable/disable debug mode
  14. (
  15. # ------------------------------ BEGIN OPTIONS ------------------------------- #
  16.  
  17. # time (in secs) between checks for failed/stopped/unresponsive openvpn clients
  18. INTERVAL=60
  19.  
  20. # internet host used for ping checks
  21. PING_HOST='8.8.8.8'
  22.  
  23. # time (in secs) between ping checks
  24. PING_INTERVAL=10
  25.  
  26. # maxmium number of ping checks before being considered a failure
  27. PING_MAXTRY=3 # (3 recommended, 0 disables ping checks)
  28.  
  29. # ------------------------------- END OPTIONS -------------------------------- #
  30.  
  31. # ---------------------- DO NOT CHANGE BELOW THIS LINE ----------------------- #
  32.  
  33. # function _ping( vpn-network-interface )
  34. _ping() {
  35.     [ $PING_MAXTRY -gt 0 ] || return 0
  36.  
  37.     local i=1
  38.  
  39.     # it's best to check multiple times to prevent false negatives
  40.     while :; do
  41.         ping -qc1 -w3 -I $1 $PING_HOST &>/dev/null && return 0
  42.         [ $(( i++ )) -ge $PING_MAXTRY ] && break || sleep $PING_INTERVAL
  43.     done
  44.  
  45.     return 1
  46. }
  47.  
  48. # wait for *reliable* internet connection
  49. while ! ping -qc1 -w3 $PING_HOST &>/dev/null; do sleep 10; done
  50.  
  51. while sleep $INTERVAL; do
  52.     for i in 1 2 3 4 5; do
  53.         # only enabled openvpn clients need to be considered
  54.         [ "$(nvram get vpn_client${i}_state)" != '0' ] || continue
  55.  
  56.         # check for failed connection or unresponsive tunnel
  57.         pidof vpnclient${i} &>/dev/null && _ping tun1${i} && continue
  58.  
  59.         # fall-through means failure; restart the openvpn client
  60.         service restart_vpnclient${i}
  61.         echo "openvpn client #$i (re)started @ $(date)"
  62.     done
  63. done
  64.  
  65. ) 2>&1 | logger -t $(basename $0)[$$] &
  66. EOF
  67. chmod +x $SCRIPT
  68. }
  69.  
  70. if [ -f $SCRIPT ]; then
  71.     echo "error: $SCRIPT already exists; requires manual installation"
  72. else
  73.     create_script
  74.     echo "installed: $SCRIPT"
  75. fi
RAW Paste Data Copied