Blocking ads with a server, using dnsmasq

Remove bind9:

apt-get remove bind9

Install dnsmasq:

apt-get install dnsmasq
service dnsmasq start

Now, run a script to auto download list of ad servers:

#!/bin/sh

### short script that downloads a list of ad servers for use with
### dnsmasq to block ads.
###

# the ipaddress where we want to send the requests to, instead of the
# bannerservers

addcatcherip='192.168.1.4'
configfile=/etc/dnsmasq.conf

# the args to add to the request to the yoyo server, to tell it that we want
# a hosts file and that we want to redirect to the addcatcher
listurlargs="hostformat=nohtml&showintro=0&mimetype=plaintext"

# URL of the ad server list to download
listurl="http://pgl.yoyo.org/adservers/serverlist.php?${listurlargs}"

# location of a file where hostnames not listed can be added
extrasfile='/etc/banner_add_hosts.manual'

## command to reload dnsmasq - change according to your system
## not sure if we need this for dnsmasq
reloadcmd='/etc/init.d/dnsmasq restart'

# temp files to use
tmpfile="/tmp/.adlist.$$"
tmpconffile="/tmp/.dnsmasq.conf.$$"

# command to fetch the list (alternatives commented out)
fetchcmd="/usr/bin/wget -q -O $tmpfile $listurl"

$fetchcmd

# add the extras
 [ -f "$extrasfile" ]  && cat $extrasfile >> $tmpfile

# check the temp file exists OK before overwriting the existing list
if  [ ! -s $tmpfile ]
then
echo "temp file '$tmpfile' either doesn't exist or is empty; quitting"
exit
fi

# get a fresh list of ad server addresses for dnsmasq to refuse
cat $configfile | grep -v "address=" > $tmpconffile

while read line; do
    ADDRESS="/${line}/${addcatcherip}"
    echo "address=\"${ADDRESS}\"" >> $tmpconffile
done < $tmpfile

mv $tmpconffile $configfile
$reloadcmd
rm $tmpfile
exit

Name it as update_bannerhosts

Now, copy it to /usr/local/bin/update_bannerhosts

cp update_bannerhosts /usr/local/bin/
chmod 755 /usr/local/bin/update_bannerhosts

Add it to cron:

0 1 * * * /bin/sh /usr/local/bin/update_bannerhosts

Run it for the first time:

/usr/local/bin/update_bannerhosts