Skip to content

Instantly share code, notes, and snippets.

@glesica
Last active January 18, 2024 17:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save glesica/5335522 to your computer and use it in GitHub Desktop.
Save glesica/5335522 to your computer and use it in GitHub Desktop.
A quick shell script that will automatically update a Linux HOSTS file to block ads and malicious domains.
#!/usr/bin/env sh
# Filename: update-hosts.sh
# Author: George Lesica <george@lesica.com>
# Description: Replaces the HOSTS file with a customized version that blocks
# domains that serve ads and malicious software, creating a backup of the old
# file.
HOSTS_URL="http://someonewhocares.org/hosts/zero/hosts"
NEW_HOSTS="hosts"
HOSTS_PATH="/etc/hosts"
# Check for root
if [ "$(id -u)" -ne "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
# Grab hosts file
wget -O $NEW_HOSTS $HOSTS_URL
# Backup old hosts file
cp -v $HOSTS_PATH ${HOSTS_PATH}.bak$(date -u +%s)
cp -v $NEW_HOSTS $HOSTS_PATH
# Clean up old downloads
rm $NEW_HOSTS*
@Eliastik
Copy link

Eliastik commented Dec 29, 2017

I forked your script and I added the support of multiple hosts sources, initial host file and others fixes: https://gist.github.com/Eliastik/f4a3573b43839c64c35b5e80491aa074

@CHJ85
Copy link

CHJ85 commented May 23, 2023

How can I run this script without being prompted for root?
I want to set this up so it can update the hosts file once a day.

@metametapod
Copy link

Another option that preserves existing entries instead of overwriting /etc/hosts: https://gist.github.com/metametapod/4c4a7a9c888343fc6e722f8ed77aa763

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