Automate Ad Blocking hosts file update on Router with DD-WRT Micro Edition

Your DD-WRT enabled router can be configured to block ads as described in the Ad Blocking article.

For non-Micro DD-WRT versions the ad blocking hosts file on the router can be updated automatically by a custom shell script that you then execute as a cron job, all on the router itself. However, the Micro editions of DD-WRT are too limited and the only way to update the router’s hosts file is by manually copying it to the router via a telnet session, where you basically copy/paste the entire hosts file contents in the telnet screen. However, after each router reboot you will need to repeat the whole process.

So since you can’t automate this process on the router, it has to be done somewhere else. For instance if you have a Linux/UNIX server on your network, you could write a shell script that downloads the ad blocking hosts file and then uploads it to the router. You can then add this script to a cron job, for instance to run every day at 1am like this:

0 1 * * * /home/user/router_ad_block.sh

Here is an example of what this script may look like:

echo "Downloading hosts file..."
wget -O - http://winhelp2002.mvps.org/hosts.txt | grep 127.0.0.1 |
sed '2,$s/[[:space:]]*#.*$//g;' |
grep -v localhost | tr ' ' '\t' |
tr -s '\t' | tr -d '\015' | sort -u >/tmp/hosts.tmp

ln=`cat /tmp/hosts.tmp | wc -l`
if [ ${ln} -lt 10 ]; then
  echo "Invalid hosts file."
  exit
fi

# kill DNS service and upload hosts file
echo "Uploading hosts file to router..."
(
echo open 192.168.1.1
sleep 1
echo "admin"
sleep 1
echo "password"
sleep 1
echo "cd /tmp"
sleep 1
echo "killall dnsmasq"
sleep 5
echo "cat > hosts"
sleep 1
cat /tmp/hosts.tmp
sleep 10
) | telnet > /dev/null
rm /tmp/hosts.tmp

# start DNS service.
echo "Starting DNS service on router..."
(
echo open 192.168.1.1
sleep 1
echo "admin"
sleep 1
echo "password"
sleep 1
echo "dnsmasq --conf-file=/tmp/dnsmasq.conf --addn-hosts=/tmp/hosts"
sleep 5
echo "exit"
sleep 1
) | telnet > /dev/null

echo "Done."

Leave a Reply

Your email address will not be published. Required fields are marked *

*