Python script to update hosts file for ad blocking

There are many ways to do Ad Blocking. Probably the most popular one being an ad blocking add-on or extension to your browser. These are available for at least Chrome/Chromium and Firefox.
The trouble with adding stuff to the browser is that it also makes the browser more resource heavy. In the world of mobile computing, especially real mobile computers that can multi-task and do stuff that "proper computers" can do, every resource counts. One of these computers is the Nokia N900 running Maemo Linux.
This is where hosts files come in. The default Maemo browser (and the Firefox Mobile that is also available) do have AdBlock+ extensions available. I however like to keep the browser as light and responsive as possible.
Excerpt from Wikipedia about hosts files:This method exploits the fact that most operating systems store a file with IP address, domain name pairs which is consulted by most browsers before using a DNS server to look up a domain name. By assigning the local 127.0.0.1 IP number to known ad servers the user directs traffic intended to reach those ad servers to the local machine. Running a suitable web server locally the ad content can be replaced with anything the user wishes. For instance if the web server sends a blank html page for any request the ads completely disappear from the pages they were originally intended to appear on.
There are lots of different ready compiled hosts files for offer that contain the majority of major advertisement and banner servers, effectively removing them from web pages. One of these is updated at mvps.org. To automate the process of regular updates of this file, I've made a small Python script to retrieve the newest version and add the content to your /etc/hosts file. This script can be run manually or scheduled to run in Alarmed or Cron like I have done.
The script is designed for Linux distributions that have their hosts file in /etc/hosts, for example Maemo, Ubuntu, Fedora, etc. Just save the script anywhere on your file structure (I prefer to keep all mine in /opt/scripts) and as root type "python [path to script]/gethosts.py" to update your hosts file. If not as root, add "sudo" in the front to run the script with root permissions. Only root has editing rights to /etc/hosts by default so the script will give an error if it cannot write to the hosts file.
Download the script here.












Comments (post a comment)