Linux / Unix checks if VPN connection is active / up
I have some code that detects if the 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"
then
echo "VPN up"
else
echo "VPN down"
fi
exit 0
Now I am trying to rewrite the code to work with PPTP or IPSEC connection. I have tried:
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 doesn't work. Is there any other way to detect PPTP or IPSEC connection?
source to share
The next script will be:
- Run ISPConnectivity.sh script every 5 minutes. This will mean that the VPN tunnel will not work for more than 5 minutes.
- Check if there is a tun interface and run the vpn script if there is one.
- Check the connection if the tun0 interface is inserted. It tests ping on 2 public IPs (if I get at least one response from one of the tested IPs, I consider it successful) and all of them should not run the vpn script. I ran ping tests on multiple hosts to prevent the vpn script from running if the ping test on 1 IP fails.
- Send all failure output to a file in my home directory. I don't need to see if any test passed.
Sudo crontab content:
*/5 * * * * /home/userXXX/ISPConnectivity.sh >> /home/userXXX/ISPConnectivity.log 2>&1
ISPConnectivity.sh script content:
#!/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 request
totalcount=0
COUNT=4
DATE=`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"
then
echo $DATE tun0 down
sudo /home/userXXX/startVPN.sh start
else
for myHost in $HOSTS;
do
count=`ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }'`
totalcount=$(($totalcount + $count))
done
if [ $totalcount -eq 0 ]
then
echo $DATE $totalcount "fail"
sudo /home/userXXX/startVPN.sh start
#else
# echo $DATE $totalcount "pass"
fi
fi
source to share
The operator echo
is wrong. As @unwind says, single quotes (') should be backtics (`). Your current code is sending a literal value ifconfig ppp0
to grep, which does nothing useful.
But you don't really need backtists either. You can simply send the output of the directory ifconfig
to grep
; using echo
doesn't give you anything:
if ifconfig ppp0 | grep -q "00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00"; then
echo ppp connection is up
fi
source to share