Auto-Respawn Networking

This Netguard script was delivered on DebianEdu ?MailingList under GPL 2.0. Called from time to time as cronjob, it tests if networking is still working. Otherwise, it restarts networking services.

It is usefull

#
# Author: Michiel Eghuizen (Eduwijs)
# Date:   2006-05-21
# Licence: GPL 2.0
# Changelog: Cf. wiki history of http://wiki.debian.org/DebianEdu/HowTo/AutoNetRespawn
#
# A tool which must be run in a cron job, to monitor the network.
# If the network is down, it will restart the network script,
# so you IP settings will be reloaded and it will execute some custom commands,
# for example stop the OpenVPN server, or reset the IPTables script.

LOGFILE="/var/log/netguard.log"
CHECKIP="10.0.2.1"                 ## Internet gateway in Skolelinux environments

NETWORKSCRIPT="/etc/init.d/networking restart"
BRIDGEUTIL="/usr/sbin/brctl"
IPTABLESSAVE="/sbin/iptables-save"

# Commands to execute when the connection is down
# This will be run before the network script is restarted
execcommands () {
    /etc/init.d/openvpn stop &> /dev/null
}

# Check if logfile exists, if not then create a new one
if [ ! -e "$LOGFILE" ]; then
    touch $LOGFILE &> /dev/null
fi

# Check if i have write permissions
if [ ! -w "$LOGFILE" ]; then
    echo "You don't have write permissions to write to the log file."
    echo "Because the log file is in this script an important file, this script will be closed."
    echo ""
    echo "Debug info:"
    echo "logfile: $LOGFILE"
    echo "user: " `whoami`

    exit 1
fi

ping -c 1 $CHECKIP > /dev/null

if [ "$?" != "0" ]; then
    echo "[NetGuard]" >> $LOGFILE
    echo "===============================" >> $LOGFILE
    echo "Status: Network is down!" >> $LOGFILE
    echo "Time: " `date` >> $LOGFILE
    echo "Current network configuration: " >> $LOGFILE
    /sbin/ifconfig >> $LOGFILE
   
    echo "Route configuration: " >> $LOGFILE
    /sbin/route >> $LOGFILE

    if [ -e "$BRIDGEUTIL" ]; then
        echo "Bridge configuration: " >> $LOGFILE
        $BRIDGEUTIL show >> $LOGFILE
    fi

    if [ -e "$IPTABLESSAVE" ]; then
        echo "IP tables: " >> $LOGFILE
        $IPTABLESSAVE >> $LOGFILE
    fi

    execcommands

    echo "Network script restart output: " >> $LOGFILE
    $NETWORKSCRIPT >> $LOGFILE

    ping -c 1 $CHECKIP > /dev/null
   
    if [ "$?" == "0" ]; then
        echo "Restart status: successful" >> $LOGFILE
    else
        echo "Restart status: FAILED" >> $LOGFILE
    fi
   
    echo "===============================" >> $LOGFILE
    echo "" >> $LOGFILE
fi