Skip to content

Instantly share code, notes, and snippets.

@gsanders5
Last active April 9, 2017 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsanders5/33f22f29602387b0ff1b5a98f5338ef2 to your computer and use it in GitHub Desktop.
Save gsanders5/33f22f29602387b0ff1b5a98f5338ef2 to your computer and use it in GitHub Desktop.
Start and maintain am openvpn connection
#!/bin/bash
# Test an IP address for validity:
# Usage:
# valid_ip IP_ADDRESS
# if [[ $? -eq 0 ]]; then echo good; else echo bad; fi
# OR
# if valid_ip IP_ADDRESS; then echo good; else echo bad; fi
#
function valid_ip()
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
# Set the origional IP address, without the proxy
nmcli con down "79cb5c38-f63e-4abe-9936-7cd1bcee4fb3" # Double check the proxy is offline
origip="$(curl -s http://ipv4.icanhazip.com/)"
# If run directly, execute some tests.
if valid_ip $origip; then
echo "Valid IP"
else
echo "Invalid IP"
exit
fi
# Connect the the proxy without error on first run
nmcli con up "79cb5c38-f63e-4abe-9936-7cd1bcee4fb3"
while true
do
if [ "$(curl -s http://ipv4.icanhazip.com/)" == "$origip" ]; then
echo "Error, IP has changed... reconnecting to the proxy"
nmcli con down "79cb5c38-f63e-4abe-9936-7cd1bcee4fb3"
sleep 1
nmcli con up "79cb5c38-f63e-4abe-9936-7cd1bcee4fb3"
# else
# echo "Still behind a proxy"
fi
sleep 1800
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment