Skip to content

Instantly share code, notes, and snippets.

@ayanamist
Created October 27, 2011 13:02
Show Gist options
  • Select an option

  • Save ayanamist/1319483 to your computer and use it in GitHub Desktop.

Select an option

Save ayanamist/1319483 to your computer and use it in GitHub Desktop.
OpenVPN reconnect Bash script
#!/bin/bash
# configuration
DEVICE="tap0"
USERNAME="twitter"
PASSWORD="twitter"
# check configuration and environment
if [ -z $DEVICE ]; then
echo You must specific DEVICE first.
exit 1
fi
if [ -z $USERNAME ]; then
echo You must specific USERNAME first.
exit 1
fi
if [ -z $PASSWORD ]; then
echo You must specific PASSWORD first.
exit 1
fi
which expect > /dev/null
if [ $? -gt 0 ]; then
echo You must install "expect" package first.
exit 1
fi
# check availability of url, if number of successful ping is larger than half, stop.
PING_NUM=`ping -n -c 10 twitter.com|grep received|awk '{ print $4 }'`
if [ $PING_NUM -gt 5 ]; then
exit 0
fi
# delete related rule from iptables
RULENUM=`iptables -t nat -L POSTROUTING -n --line-numbers|grep '199.59.148.0'|awk '{ print $1;exit }'`
if [ -n "$RULENUM" ]; then
iptables -t nat -D POSTROUTING $RULENUM
fi
# stop openvpn service if any
service openvpn stop
# start openvpn service
expect -c "
set send_human {.1 .3 1 .05 2}
spawn service openvpn start
expect {
\"sername\" {
send -h \"$USERNAME\\n\"
exp_continue
}
\"assword\" {
send -h \"$PASSWORD\\n\"
exp_continue
}
eof {
wait
}
}
exit
"
# get openvpn ip
for i in `seq 5`; do
sleep 3
# check if openvpn is running
ifconfig $DEVICE > /dev/null 2>&1
if [ $? -eq 0 ]; then
OPENVPN_IP=`ifconfig $DEVICE | grep inet | sed '2d'| awk '{ print $2}'| awk -F: '{ print $2 }'`
break
fi
done
# add rule to iptables
if [ -n "$OPENVPN_IP" ]; then
iptables -t nat -A POSTROUTING -d 199.59.148.0/255.255.252.0 -j SNAT --to-source $OPENVPN_IP
else
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment