Skip to content

Instantly share code, notes, and snippets.

Last active Jun 5, 2020
What would you like to do?
Save some DNS traffic by adding a specific host to your /etc/hosts file, refresh it via cron
# Use at your own risk. This script assumes some defaults and things may break.
# Requires 'dnsutils' package which contains 'dig'.
# Script looks up IPv4 and IPv6 addresses for the provided host and adds them to the local
# hosts file. Removes old entries. If addresses cannot be resolved then nothing gets
# addded (but old entries get removed!).
# Call script with 'sudo fully.qualified.dom'
# Can be added to a crontab with root permissions
# for however often you want to refresh the cached IP.
# Exemplary crontab entry: '*/20 * * * * sudo /full/path/ fully.qualified.dom'
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root."
exit 1
dns=$(grep "nameserver" /etc/resolv.conf | head -1 | cut -d ' ' -f 2)
ipv4addr=$(dig +short "$host" @$dns | grep -v '\.$' | head -1)
ipv6addr=$(dig +short AAAA "$host" @$dns | grep ':' | head -1)
grep -v "$host" /etc/hosts > /etc/hosts.bkp
[[ ! -z "${ipv4addr// }" ]] && echo "$ipv4addr $host" >> /etc/hosts.bkp
[[ ! -z "${ipv6addr// }" ]] && echo "$ipv6addr $host" >> /etc/hosts.bkp
cp -f /etc/hosts.bkp /etc/hosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment