Skip to content

Instantly share code, notes, and snippets.

@kolpanic
Last active August 18, 2023 13:02
Show Gist options
  • Save kolpanic/01fa41c163467483f43a67e44f8cfc79 to your computer and use it in GitHub Desktop.
Save kolpanic/01fa41c163467483f43a67e44f8cfc79 to your computer and use it in GitHub Desktop.
Block unwanted parasites by redirecting them to `0.0.0.0`
#!/bin/bash
# Downloads Steven Black's "Unified hosts + fakenews" hosts file
# and replaces the existing system hosts file
# https://github.com/StevenBlack/hosts
#
# If you want to make any manual persistent changes to the system hosts
# file, run this script first, then make sure that the change is backed up to
# /etc/hosts.orig
if [ "$(whoami)" != "root" ]; then
echo "Sorry, this script must be run as root."
exit 1
fi
# Back up the original hosts file if necessary
if [ ! -f /etc/hosts.orig ]; then
cp /etc/hosts /etc/hosts.orig
fi
# Download the hosts file, convert the file encoding to UTF-8 and the DOS line endings to UNIX, then replace the existing hosts file
curl https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews/hosts |
iconv -t UTF8//IGNORE -f ASCII |
tr -d '\r' > /etc/hosts
# Exclude items that break sites
# Uncomment the following line and duplicate & edit as necessary
#sed -i '' 's/0.0.0.0 www.example.com/#0.0.0.0 www.example.com/g' /etc/hosts
# Flush DNS
dscacheutil -flushcache; killall -HUP mDNSResponder
@kolpanic
Copy link
Author

Here's a complementary script to restore the backed up hosts file:

# Restore the original hosts file

if [ "$(whoami)" != "root" ]; then
	echo "Sorry, this script must be run as root."
	exit 1
fi

if [ -f /etc/hosts.orig ]; then
	rm /etc/hosts
	cp /etc/hosts.orig /etc/hosts

	# Flush DNS
	dscacheutil -flushcache; killall -HUP mDNSResponder
fi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment