Automatically adding lists of blocked zones to PiHole (BASH)

Having PiHole pull a list of blocked ad domains is simple enough, but it gets a little bit more complicated if you want to pull a list of blocked zones (e.g. a block for *.foo.com)

This script (originally created in ADBLK-12) can be run as a cron to periodically pull down a list of zones, turn them into regexes and feed them into pihole so that every label under that name is also blocked

Details

Snippet

#!/bin/bash
#
# Pull down a list of blocked zones (implemented in ADBLK-12)
# then translate them into regex's to feed into Pihole
#
# This is better than blocking upstream, as a block in FTL will
# result in the adblock counter increasing
#
# Copyright (c) 2019 B Tasker
# Released under GNU GPL V3 - see https://www.gnu.org/licenses/gpl-3.0.txt
# 
#

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Create a temp file
OUT="$(mktemp)"
> $OUT

# Fetch the blocked zone file
for zone in `curl -s "https://www.bentasker.co.uk/adblock/blockedzones.txt"`
do
    regex=$(echo "$zone" | sed 's~\.~\\\.~g')
    echo "^.+\.$regex\$" >> $OUT
done

count=$(wc -l "$OUT" | cut -d\  -f1)

if [ $count -gt 0 ]
then

    # Check the files actually differ
    cd /etc/pihole
    diff -u "$OUT" regex.list > /dev/null
    if [ "$?" == "1" ]
    then
        # Files differ. Make a backup
        cp -n regex.list regex.list.old
        cat "$OUT" > regex.list

        # Tell Pihole to reload the regexes
        echo ">recompile-regex" | nc -q1 localhost 4711
    fi
fi

rm -f "$OUT"

Usage Example

echo "0 */2 * * *    root    /root/update_ads.sh" | sudo tee /etc/cron.d/update_ads