Skip to content

Instantly share code, notes, and snippets.

@dfasolin
Last active January 8, 2016 09:24
Show Gist options
  • Save dfasolin/afa72f991a7c5276b09e to your computer and use it in GitHub Desktop.
Save dfasolin/afa72f991a7c5276b09e to your computer and use it in GitHub Desktop.
Automatically update local hosts file with hosts-file.net
#!/usr/bin/env sh
# Filename: update-hosts.sh
# Authors: George Lesica <[email protected]>
# Danilo Fasolin Salmazio <[email protected]>
# Description: Replaces the HOSTS file with a customized version (hosts-file.net) that blocks
# domains that serve ads and malicious software, creating a backup of the old
# file.
# Improvements: Add the partial file, a /etc/hosts_dev with some development hosts and creates
# a logfile
#
# hosts_dev sample:
# ########################################################
# ###################### HOSTS DEV #######################
# ########################################################
# 192.168.33.10 dev
# 192.168.33.11 sample-dev.com
#
# Add this file to cron with crontab -e (root access)
# sudo -s
# crontab -e
# min hr mday month wday command
# 00 21 * * 5 /var/root/update-hosts.sh >> /var/log/update_hosts.log 2>&1
#
# The cron execution creates a logfile in /var/log/update_hosts.log
HOSTS_URL="http://hosts-file.net/download/hosts.txt"
NEW_HOSTS="hosts"
HOSTS2_URL="http://hosts-file.net/hphosts-partial.asp"
NEW_HOSTS2="hosts2"
HOSTS_PATH="/etc/hosts"
# Add all dev hosts in /etc/hosts_dev file
HOSTS_DEV="/etc/hosts_dev"
LOGFILE="/var/log/update_hosts.log"
# Check for root
if [ "$(id -u)" -ne "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
# Remove the old LOGFILE
rm -f $LOGFILE
# Grab hosts files
/usr/local/bin/wget -O $NEW_HOSTS $HOSTS_URL
/usr/local/bin/wget -O $NEW_HOSTS2 $HOSTS2_URL
# Remove old Backup and create a new one of hosts file
rm -f ${HOSTS_PATH}.bak*
cp -v $HOSTS_PATH ${HOSTS_PATH}.bak$(date -u +%s)
cp -v $NEW_HOSTS $HOSTS_PATH
# Add the diff and developer hosts
/bin/cat $NEW_HOSTS2 >> $HOSTS_PATH
/bin/cat $HOSTS_DEV >> $HOSTS_PATH
# Clean up old downloads
rm $NEW_HOSTS*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment