IPTable Kill Switch Script to detect and reset OpenVPN automatically

I had implemented an IPTABLE Killswitch with OpenVPN at this link
KillSwitch

This solution has been working great, however when the OPENVPN fails and the kill switch starts blocking traffic, there is no way to know without manually checking.

I would like some help in developing a script or solution that can detect when their is not an IPaddress, then run script to restart OpenVPN.

My thoughts would be the script would occassionally run:
curl ipinfo.io/ip
If returns result
Then exit
else
sudo systemctl stop openvpn
sudo systemctl start openvpn

This seems easy enough in concept but I don’t know where to start writting the script in OSMC or if there is an easier solution.

This might help you:

#!/bin/bash

# Test an IP address for validity, 
function valid_ip()
{
    local  ip=$1
    local  stat=1

    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
            && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
    fi
    return $stat
}
MYIP=$(curl -s http://ipinfo.io/ip)

if valid_ip $MYIP; then 
       fill in what you like
else
      fill in the other option
fi

Hi,

2 ways of doing this, one way is to use systemd; details can be found here:

being as you specifically requested a script an other option could be:

#!/bin/bash
ps -ef | grep -v grep | grep openvpn
if [ $? -eq 1 ] ; then
systemctl restart openvpn
fi

The script checks to see if openvpn is still running and if not restarts it. Just set a cron job to check how often required.

Thanks Tom.

1 Like

Thank you! I will use try the SYSTEMD solution.
Once again I appreciate the assistance.

Hi JJS78,

I had a similar problem, in that OpenVPN failed for me. But Tom’s suggestion of using systemd worked for me.

Mark

2 Likes