Reputation: 2087
I am trying to make my openvpn client restart if it is not able to ping the destination 4.2.2.2 every 60 seconds, if it is then do nothing. Here is what I have. I want to to be continuously running also.I am running this on Alpine Linux. Any help is greatly appreciated.
#!/bin/sh
#This is a script to continuously do 5 pings to 4.2.2.2
#every 60 seconds to keep the tunnel up if pings fail,
#then it will restart the openvpn process. And record the
#time it failed.
PING=ping -w 5 4.2.2.2
exec &> /var/log/ping_SLA
while true
do
if
#ping returns a fail value
[ $PING -eq 0 ];
sleep 60s
then
#Execute commands
date > /var/log/ping_SLA_Fail
rc-service openvpn stop
killall -9 openvpn
rc-service openvpn start
sleep 30s
else
# colon is a null and is required
:
fi
done
Upvotes: 2
Views: 14963
Reputation: 5891
You have to run the ping
command and then test its exit value:
ping -w 5 4.2.2.2 > /dev/null 2>&1
if [[ $? -eq 0 ]]; then
echo "Ping worked"
else
echo "Ping failed"
fi
Upvotes: 2
Reputation: 5972
man ping:
-c count
Stop after sending count ECHO_REQUEST packets. With deadline option, ping waits for count ECHO_REPLY packets, until the timeout expires.
-s packetsize
Specifies the number of data bytes to be sent. The default is 56, which translates into 64 ICMP data bytes when combined with the 8 bytes of ICMP header data.
-w deadline
Specify a timeout, in seconds, before ping exits regardless of how many packets have been sent or received. In this case ping does not stop after count packet are sent, it waits either for deadline expire or until count probes are answered or for some error notification from network.
-W timeout
Time to wait for a response, in seconds. The option affects only timeout in absense of any responses, otherwise ping waits for two RTTs.
So we have:
ping -c 1 -s 1 -W 1 4.2.2.2 1>/dev/null 2>&1 #The fast way to ping
#OR : nmap -sP 1 4.2.2.2 1 1>/dev/null 2>&1 #The fastest way to ping
if [ $? -eq 0 ]; then
date >> /var/log/ping_SLA_Fail
rc-service openvpn stop
killall -9 openvpn
rc-service openvpn start
sleep 30
elif [ $? -ne 0 ]; then
.
.
.
fi
Upvotes: 3
Reputation: 3646
I'm not familiar with any -w
option with ping.
Use the -c
option with your ping command to determine the number of ICMP echo requests to send.
Something like this should work:
if ! ping -c 5 4.2.2.2 &> /dev/null; then
date >> /var/log/ping_SLA_Fail
rc-service openvpn stop
killall -9 openvpn
rc-service openvpn start
fi
sleep 60
Upvotes: 4