-
-
Save giddyhup/48e969ac71186f679075b6085c215c7f to your computer and use it in GitHub Desktop.
Save some DNS traffic by adding a specific host to your /etc/hosts file, refresh it via cron
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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