I have a code which detects if OpenVPN connection is up or down:
if echo 'ifconfig tun0' | grep -q "00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00"thenecho "VPN up"elseecho "VPN down"fiexit 0
now I'm trying to re-write the code to work with PPTP or IPSEC connection. I've tried to do:
if echo 'ifconfig ppp0' | grep -q "00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00"
or the same with ipsec but does not work. Is there any other way to detect PPTP or IPSEC connection?
Best Answer
That echo
statement is erroneous. As @unwind says, the single quotes (') should be backtics (`). Your current code is sending the literal value ifconfig ppp0
to grep, which doesn't do anything useful.
But you don't actually need the backtics, either. You can just send the output of ifconfig
to grep
directory; using echo
doesn't get you anything:
if ifconfig ppp0 | grep -q "00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00"; thenecho ppp connection is upfi
The following script will:
- Run the ISPConnectivity.sh script every 5 minutes. This will mean that the VPN tunnel will not be down for more than 5 minutes.
- Check if the tun interface is down, and start the vpn script if it is.
- Check connectivity if the tun0 interface is up. It does ping tests on 2 Public IPs (if I get even a single response from 1 of the IPs tested, I consider this a success ), and all have to fail to run the vpn script. I ran ping tests on multiple hosts to prevent the vpn script from starting in case the ping test failed on 1 IP.
- Send all failure output to a file in my home directory. I do not need to see if any test succeeded.
Contents of sudo crontab:
*/5 * * * * /home/userXXX/ISPConnectivity.sh >> /home/userXXX/ISPConnectivity.log 2>&1
Contents of ISPConnectivity.sh script:
#!/bin/bash # add ip / hostname separated by white space#HOSTS="1.2.3.4"HOSTS="8.8.8.8 4.2.2.4"# no ping requesttotalcount=0COUNT=4DATE=`date +%Y-%m-%d:%H:%M:%S`if ! /sbin/ifconfig tun0 | grep -q "00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00"thenecho $DATE tun0 downsudo /home/userXXX/startVPN.sh startelsefor myHost in $HOSTS;docount=`ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }'`totalcount=$(($totalcount + $count))doneif [ $totalcount -eq 0 ]thenecho $DATE $totalcount "fail"sudo /home/userXXX/startVPN.sh start#else# echo $DATE $totalcount "pass"fifi
You can also check with the nmcli command, to check if VPN is running or not.
nmcli c show --active | grep vpn
I'm actually looking into more flexible solution eg:
MyIP=$(curl http://api.ipify.org/?format=text)if [ "$MyIP" != "MYORYGINALIP" ]thenecho "IPSEC VPN is Running - " $MyIPelseecho "IPSEC VPN is Not Running - " $MyIPfiexit 0
what about that? can I improve it any way?
ip route list table 220 if Ip address shown -> VPN connection established, none -> no VPN
or
if [ "0" == ifconfig | grep wlan0 | wc -l
]; then echo "NO wlan0 has no VPN"; else echo "YES wlan0 has VPN"; fi