Created
September 5, 2019 08:56
-
-
Save katoozi/4ae8392de3181a502ddc471c1474d5f9 to your computer and use it in GitHub Desktop.
ipsec vpn connection script. work with https://github.com/hwdsl2/setup-ipsec-vpn
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
#!/usr/bin/env bash | |
# output text colors | |
RED='\033[0;31m' | |
GREEN='\033[0;32m' | |
NC='\033[0m' | |
detect_current_connection(){ | |
result="$(ip route | grep 'default dev ppp' | awk '{print $3}')" | |
} | |
write_to_connection_file(){ | |
file="/var/run/xl2tpd/l2tp-control" | |
if [ -f $file ]; then | |
sudo chmod 777 $file | |
echo "$1 myvpn" > /var/run/xl2tpd/l2tp-control | |
else | |
sudo sh -c "echo '$1 myvpn' >> /var/run/xl2tpd/l2tp-control" | |
fi | |
} | |
connect () { | |
detect_current_connection | |
con=$result | |
if [[ $con == ppp* ]]; then | |
disconnect | |
fi | |
echo -e "${GREEN}Attempt to connect...${NC}" | |
DefaultRoute=$(/sbin/ip route | awk '/default/ { print $3 }') | |
MyPublicIp="$(dig +short myip.opendns.com @resolver1.opendns.com)" | |
sudo service strongswan restart | |
sudo service xl2tpd restart | |
sudo ipsec up myvpn | |
write_to_connection_file c | |
# $MY_SERVER_IP was set permanently in /etc/environment | |
vpn_server_ip_route="$(ip route show $MY_SERVER_IP | wc -l)" | |
my_public_ip_route="$(ip route show $MyPublicIp | wc -l)" | |
if [ $vpn_server_ip_route -eq 0 ] | |
then | |
sudo route add $MY_SERVER_IP gw $DefaultRoute | |
elif [ $my_public_ip_route -eq 0 ] | |
then | |
sudo route add $MyPublicIp gw $DefaultRoute | |
fi | |
echo -e "${GREEN}Waiting For Service To Start...${NC}" | |
while true | |
do | |
con="$(ip route | grep 'ppp' | awk '{print $3}')" | |
if [[ $con == ppp* ]]; then | |
sudo route add default dev $con | |
echo -e "${GREEN}Connected to $con${NC}" | |
break | |
fi | |
sleep 1 | |
done | |
} | |
disconnect () { | |
echo -e "${GREEN}Attempt to disconnect...${NC}" | |
detect_current_connection | |
con=$result | |
if [[ $con == ppp* ]]; then | |
sudo route del default dev $con | |
write_to_connection_file d | |
sudo ipsec down myvpn | |
echo -e "${GREEN}Disconnected From $con${NC}" | |
else | |
echo -e "${RED}No Device Detetcted...${NC}" | |
fi | |
} | |
action=${1:-c} | |
if [ "$action" = "c" ] | |
then | |
connect | |
elif [ "$action" = "d" ] | |
then | |
disconnect | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment