DDNS failover script

A useful script for automating dynamic DNS updates when you are serving on multiple IP addresses.

#!/bin/bash
EMAIL=me@mydomain.co.uk
HOSTMASTER=hostmaster.mydomain.co.uk
KEY=yxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxgQ==
SERVER=ns1.mydomain.co.uk
ZONE=otherdomain.co.uk
DOMAIN=ddns.otherdomain.co.uk
IPV4LIST="10.0.0.1 10.0.0.2"
IPV6LIST=""
TESTPAGE=ddns.asp
MAILER=/usr/exim/bin/exim
ERRORLIST="error,unavailable,bad request"
failcode=0
function TestHostForURL () {
        # Parameters
        # $1 - hostname
        # $2 - IP URL
        echo curl --connect-timeout 5 --header "Host: $1 " $2
        out=$( curl --connect-timeout 5 --header "Host: $1 " $2 2>&1 )
        # Assign the exit value to c
        c=$?
        if [ 0 -eq $c ]
        then
                bad=0
                # Save IFS before we temporarily change it
                OIFS=$IFS
                IFS=','
                arr=$ERRORLIST
                for e in $arr
                do
                        echo $out | grep -i $e 2>&1 1>/dev/null
                        c=$?
                        if [ 0 -eq $c ]
                        then
                                # Error found
                                bad=1
                                break
                        fi
                done
                # restore IFS
                IFS=$OIFS
        else
                bad=2
                # Nothing there
        fi
        echo $1 $2 $bad
        failcode=$bad
}
f=/tmp/$RANDOM
rm -f $f
touch $f
echo    "server $SERVER" >> $f
echo    "zone $ZONE." >> $f
echo    "update delete $DOMAIN. A" >> $f
if [ $IPV6LIST -ne "" ]
then
        echo    "update delete $DOMAIN. AAAA" >> $f
fi
for IP in $IPV4LIST
do
        TestHostForURL "$DOMAIN" "http://$IP/$TESTPAGE"
        if [ $failcode -eq 0 ]
        then
                echo    "update add $DOMAIN. 60 A $IP" >> $f
        fi
done
for IP in $IPV6LIST
do
        TestHostForURL "$DOMAIN" "http://$IP/$TESTPAGE"
        if [ $failcode -eq 0 ]
        then
                echo    "update add $DOMAIN. 60 AAAA $IP" >> $f
        fi
done
echo "show" >> $f
echo "send" >> $f
cat $f
if [ ! -e "/etc/ddns/$DOMAIN" ]
then
        cp $f /etc/ddns/$DOMAIN
fi
diff /etc/ddns/$DOMAIN $f
if [ 0 -ne $? ]
then
        # differ
        echo "Doing update"
        echo "Subject: DDNS UPDATE\n" | cat $f | $MAILER $EMAIL
        nsupdate -y "$HOSTMASTER:$KEY" << EOF
`cat $f`
EOF
        logger $f
        cp $f /etc/ddns/$DOMAIN
        rm -f $f
fi

 

This entry was posted in Uncategorized. Bookmark the permalink.

Comments are closed.