quarta-feira, 2 de março de 2011

script for change route following dynamic ip

#!/bin/bash
# filename: dynhost.sh
#
# this script is to change the route, following the change of client Dynamic IP
# using dyndns.org or other
##
# written by Olympio Renno http://www.linkedin.com/in/olympiorenno
# based on scrit firewall-dynhosts.sh by: Dave Horner
# (http://dave.thehorners.com)
# Released into public domain.
#
# Run this script in your cron table to update ips.
# /5 * * * * /sbin/dynhost.sh "host1".dyndns.org
# /5 * * * * /sbin/dynhost.sh "host2".dyndns.org
#
#

HOST=$1
GATEWAY="201.27.129.1"
HOSTFILE="/root/dynhosts/host-$HOST"
ROUTE="/sbin/route"
DATA=`date +%Y-%m-%d-%H.%M`
ARQLOG="/var/log/dynhost.log"

# check to make sure we have enough args passed.
if [ "${#@}" -ne "1" ]; then
echo "$0 hostname x" >> $ARQLOG
echo "You must supply a hostname to update route."
exit
fi

# lookup host name from dns tables
IP=`/usr/bin/dig +short $HOST | /usr/bin/tail -n 1`
if [ "${#IP}" = "0" ]; then
echo "Couldn't lookup hostname for $HOST, failed." >> $ARQLOG
exit
fi

OLDIP=""
if [ -a $HOSTFILE ]; then
OLDIP=`cat $HOSTFILE`
fi

if [ $OLDIP = $IP ]; then
exit
fi

# save off new ip.
echo $IP>$HOSTFILE

echo "Updating $HOST in iptables."
if [ "${#OLDIP}" != "0" ]; then
echo "$DATA new ip = $IP old ip = $OLDIP" >> $ARQLOG
echo "Removing old rule ($OLDIP)" >>$ARQLOG
`$ROUTE del $OLDIP gw $GATEWAY`
fi
echo "Inserting new rule ($IP)" >>$ARQLOG
`$ROUTE add $IP gw $GATEWAY`