Willkommen bei bytebang » The blog about all and nothing » Auto reconnect on dropped VPN connection

Auto reconnect on dropped VPN connection

Nov 21 2015

The Problem

One of my customers runs an external server which is connected to the main network via a simple PPTP connection. This works fine but from time to time the firewall decides to drop the connection (for whatever reason). From this moment on, the external server can not access the resources within the internal network any more. Until now we had to restart the connection by hand, but this is not very comfortable.

The Solution

The solution is easy: Whenever the external server is not able to ping an internal server then it should try to reconnect to the VPN. This can be easily automated with a simple cron job.

#!/bin/bash

# no ping request
COUNT=1

# add ip / hostname separated by white space
HOSTS="192.168.0.250"

# no ping request
COUNT=1

# do the checks
for myHost in $HOSTS
do
   count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
   if [ $count -eq "0" ]; then
      # 100% failed
      echo "Host : $myHost is down (ping failed) at $(date)"

      # If we are root the we can reconnect
      if [ $UID -eq 0 ] ; then
          echo "Killing old pppd daemon"
          killall pppd

          echo "Re-establishing the PPTP connection"
          pptp vpn.mycompany.tld call COMPANY-CONNECTION
          sleep 3

          echo "Adding the route to the PPTP network"
          route add -net 192.168.0.0 dev ppp0 netmask 255.255.255.0
      else
          echo "Run this script as root (sudo) to automatically re-establish the connection."
      fi
   else
      echo "Connection alive"
   fi
done

This script is pretty handy. If you put it into /usr/local/bin then everybody on the system should be able to call it (as long as the permissions are correct). The script pings the host(s) defined in the 7th line. If the ping is OK, the the script prints 'Connection alive'. if not then the script prints that the desired host is down. From there on the script checks if you are root user. If you are root user - which is true if you start the script via cron (by linking it to /etc/cron.hourly) or if you start it via sudo, then the script tries to reconnect to the COMPANY-CONNECTION on the firewall behind vpn.mycompany.tld.

Get Social


(c) 2017, by bytebang e.U. - Impressum - Datenschutz / Nutzungsbedingungen
-