Skip to content

Instantly share code, notes, and snippets.

@ScottJWalter
Forked from smcpeck/vpn-refresh.sh
Created June 22, 2018 08:06
Show Gist options
  • Save ScottJWalter/48e9b428aa7a752edda1a5135ac3a8e2 to your computer and use it in GitHub Desktop.
Save ScottJWalter/48e9b428aa7a752edda1a5135ac3a8e2 to your computer and use it in GitHub Desktop.
Shell script to select fastest VPN location from available list
#!/bin/bash
# Set your VPN up with this guide: https://gist.github.com/superjamie/ac55b6d2c080582a3e64
# This runs nicely on a Raspberry Pi that is setup to be your gateway.
# Requires: speedtest-cli, openvpn
# Assuming you have config files of:
# /etc/openvpn/newyork.conf
# /etc/openvpn/chicago.conf
# /etc/openvpn/miami.conf
# Create a text file called /etc/openvpn/list.txt that looks like:
# newyork
# chicago
# miami
# Then run:
# sudo /etc/openvpn/vpn-refresh.sh /etc/openvpn/list.txt
# The fastest location will be auto detected.
if [ "$1" = "" ];
then
echo "Usage: $0 vpn-list.txt [acceptable-speed]"
echo " vpn-list.txt: text file with list of config files setup to pass to openvpn service."
echo " acceptable-speed: (Optional) minimum speed to automatically accept and skip scanning additional VPNs."
exit 1
fi
# default speed that short circuits the process to 1gbps
ACCEPTSPEED=1000
if [ "$2" != "" ];
then
ACCEPTSPEED=$2
fi
SERVERCOUNT=`wc -l "$1" | cut -d ' ' -f 1`
SPEEDGOOD=0
SERVERNUM=0
BESTSPEED=0
BESTSERVER=0
SERVERLIST=$1
echo Found $SERVERCOUNT servers in $1.
echo
testspeed ()
{
mbitdown=`speedtest-cli | grep Download | cut -d ' ' -f 2 | cut -d '.' -f 1`
if [ "$mbitdown" -gt "$BESTSPEED" ]; then
BESTSPEED=$mbitdown
BESTSERVER=$SERVERNUM
fi
echo Download speed for $SERVER is $mbitdown.
echo
}
nextserver ()
{
if [ "$SERVERNUM" -eq "$SERVERCOUNT" ]; then
exit 0
fi
((SERVERNUM++))
SERVER=`sed -n "${SERVERNUM}p" "${SERVERLIST}"`
}
resetvpn ()
{
echo -n Flipping VPN to $SERVER
# stop existing VPN connection
service openvpn stop; sleep 1;
echo -n "."
IP=`curl -s ipinfo.io/ip`
service openvpn@$SERVER start;
NEWIP=`curl -s ipinfo.io/ip`
echo -n "."
# wait 1 second while checking if IP address has changed each time
# this makes sure we are connected to the new server before moving on
while [ "$IP" = "$NEWIP" ]
do
echo -n "."
sleep 1
NEWIP=`curl -s ipinfo.io/ip`
done
echo " FLIPPED!"
}
for i in `seq 1 ${SERVERCOUNT}`;
do
if [ $BESTSPEED -lt $ACCEPTSPEED ];
then
nextserver
resetvpn
testspeed
fi
done
if [ $BESTSPEED -lt $ACCEPTSPEED ];
then
((SERVERNUM=BESTSERVER-1))
nextserver
resetvpn
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment