Toggle Hosts File Instantenously (content blocking)

PUBLISHED ON 27/09/2018 — UNIX

For a while now, I am using hosts file to block unwanted content at DNS resolve level. The steps are written for macOS, but can be easily converted for any unix like operating system.

The source for the blocked hosts file I am using is from here: https://github.com/StevenBlack/hosts

It works great, but sometimes, you just need that peice of internet that the list blocks.

Fear no more!

By adding two simple functions to your shellrc file, one can simply toggle the hosts file used.

The functions create a hardlink from /etc/hosts to a list you request to be used.

First we download the blacklist and save it as /etc/hosts-blocking:

$ cd /etc
$ wget https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts -O hosts-blocking

Next, we save the old hosts file to /etc/hosts-original:

$ sudo cp /etc/hosts /etc/hosts-original

Then just add this to your ~/.zshrc (should work for bash too):

function hosts-block {
    sudo ln -iv /etc/hosts-blocking /etc/hosts
    # Flush DNS cache
    sudo dscacheutil -flushcache;sudo killall -HUP mDNSResponder
}

function hosts-unblock {
    sudo ln -iv /etc/hosts-original /etc/hosts
    # Flush DNS cache
    sudo dscacheutil -flushcache;sudo killall -HUP mDNSResponder
}

Reload the .zshrc and you can use hosts-block and hosts-unblock to toggle.

This is for macOS, for linux, restart the nscd daemon. If you don’t have it, I higly recommend it.