Skip to content

Instantly share code, notes, and snippets.

@giddyhup

giddyhup/dnssaver.sh Secret

Last active Jun 5, 2020
Embed
What would you like to do?
Save some DNS traffic by adding a specific host to your /etc/hosts file, refresh it via cron
#!/bin/bash
# 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 dnssaver.sh 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/dnssaver.sh fully.qualified.dom'
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root."
exit 1
fi
host="$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
You can’t perform that action at this time.