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.


# no ping request

# add ip / hostname separated by white space

# no ping request

# do the checks
for myHost in $HOSTS
   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 dev ppp0 netmask
          echo "Run this script as root (sudo) to automatically re-establish the connection."
      echo "Connection alive"

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