Last active
February 27, 2023 08:11
-
-
Save Harold-D/0f2d7ae3070ceb5d10aa83e8a8c43758 to your computer and use it in GitHub Desktop.
BusyBox ash (OpenWRT) script for checking connection to VPN host over VPN interface. Restarts OpenVPN if needed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/ash | |
set -x #debugging | |
VPN_CHECK_LOG="/var/log/vpncheck.log" | |
VPN_SERVER="nl.privateinternetaccess.com" | |
VPN_INTERFACE="tun0" | |
INTERNET_INTERFACE="eth0" | |
# Check to see if the VPN server is ping-able | |
ping_success () { | |
PING_TEST=`ping -I $1 -c 4 -q $2 | grep "100% packet loss"` | |
if [ "$PING_TEST" ]; then | |
# print_to_log "NO ping from $2 over interface $1" | |
return 1 #Returning above 0 means error | |
else | |
# print_to_log "Ping test OK, $2 reacable over interface $1" | |
return 0 | |
fi | |
} | |
# Check to see if the VPN interface is still there. | |
interface_available () { | |
RESULT=`ifconfig | grep -o "$1"` | |
if [ "$RESULT" == "$1" ]; then | |
# print_to_log "$1 interface available" | |
return 0 | |
else | |
# print_to_log "Interface $1 NOT found" | |
return 1 #Returning above 0 means error | |
fi | |
} | |
# Function uses ./opevpn start if no other instance running, otherwise restart. | |
restart_vpn () { | |
if [ `pgrep openvpn` ]; then | |
# echo "using restart" | |
`/etc/init.d/openvpn restart` | |
else | |
# echo "using start" | |
`/etc/init.d/openvpn start` | |
fi | |
} | |
# Print $1 to logfile prepended with a timestamp | |
print_to_log () { | |
local DATE_TIME=`date "+%Y-%m-%d %H:%M:%S"` | |
echo "$DATE_TIME - $1" >> $VPN_CHECK_LOG& | |
} | |
if interface_available $VPN_INTERFACE; then | |
if ping_success $VPN_INTERFACE $VPN_SERVER; then | |
print_to_log "$VPN_INTERFACE found, $VPN_SERVER reachable over $VPN_INTERFACE, all OK" | |
else | |
if ping_success $INTERNET_INTERFACE $VPN_SERVER; then | |
print_to_log "$VPN_SERVER NOT ping-able over $VPN_INTERFACE but reachable over $INTERNET_INTERFACE, restarting VPN..." | |
restart_vpn | |
else | |
print_to_log "$VPN_SERVER NOT reachable over $VPN_INTERFACE or $INTERNET_INTERFACE. Internet and/or VPN Server NOT available." | |
fi | |
fi | |
else | |
if ping_success $INTERNET_INTERFACE $VPN_SERVER; then | |
print_to_log "$VPN_INTERFACE down, $VPN_SERVER reachable over $INTERNET_INTERFACE, restarting VPN..." | |
restart_vpn | |
else | |
print_to_log "$VPN_INTERFACE down, $VPN_SERVER NOT reachable over $INTERNET_INTERFACE. Internet and/or VPN Server NOT available." | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment