So I made that script I was talking about earlier

& from now on its studying all the way! More than a month left, better sooner than later! I really needed these couple of days though.. to relax the Doom stress.

ANYWHO.
This bash script checks the DHCP page of my DLink router, parses the data & inserts it into a file, using the format required by the linux “hosts” file (you know.. “/etc/hosts”) Its not pretty to look at but it gets the job done 🙂

# Variables

## Location & filename for temporary files
tMap=”/tmp/”
tFile=”t_hosts”

## Hosts location
hPath=”/etc/”
hFile=”hosts”

## Webpage with IP info page
IPpage=http://192.168.0.1/h_dhcp.html
IPu=USER
IPp=PASS
IPbase=”192.168.0.”

## Do not edit beyond this point 😉

if [[ $tMap == “” || $tMap == “/” || $tFile == “” ]]
then
echo “Thank god I didnt trust you to fill these out wisely.”
echo ” (dont get over confident tough, this is an EXTREMELY basic test!!)”
echo “At least One of the following errors was found!”
echo
echo “* the map and file variable can NOT be empty!”
echo “* the map can NOT be / (the root).”
echo “Since we re doing rm -f, these settings might cost you your OS!”
echo ” ;)”
echo
echo $map$file
exit 1
fi

# make sure there s no files that could screw the process 😉
rm $tMap$tFile* -f

# Remove old entries
grep -v $IPbase $hPath$hFile > $tMap$tFile.clean
grep -v “## Generated DHCP entries” $tMap$tFile.clean > $tMap$tFile.clean2

# Add comment
echo “## Generated DHCP entries” >> $tMap$tFile.clean2

# Get IPs from Router
wget -q –user $IPu –password $IPp $IPpage -O $tMap$tFile.router

if [[ -e $tMap$tFile.router ]]
then
grep “dDat” $tMap$tFile.router | grep -v ” dDat” > $tMap$tFile

# Parse Files
for lijn in $(cat $tMap$tFile)
do
lijn=$(echo $lijn | grep -v “dDat” | grep -v “=”)
if [[ -n $lijn ]]
then

# Get IP
ip=$(echo $lijn | grep -oE [0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3})

# Get Hostname
host=$(echo $lijn | grep -oE [“][[:alnum:]]{3,100} | grep -oE [[:alnum:]]{3,100} )

# Save
echo “$ip $host” >> $tMap$tFile.clean2

fi
done

# Replace old file by the new one
mv $tMap$tFile.clean2 $hPath$hFile
fi

# remove residual files
rm $tMap$tFile* -f

Extreme caution should be exercised when using this script. Its unsafe at so many levels.. Just to name some.. It requires certain user rights to edit the “/ect/hosts”. It uses “rm -f”. It makes use of several intermediary files. .. Dont use it on a production machine without thorough rewrite for security! (How s that for a disclaimer :))

& who needs SVN when you can post it all to blogger!

Published by Gert

Person-at-large.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: