utility-scripts/update_ip.sh

72 lines
1.8 KiB
Bash
Executable File

#!/bin/sh
cache=.update_ip.cache
server=ns1.example.com
zone=dyn.example.com
host=desktop
secret=""
iface=eth0
new_ip4=$( wget -4 -q -O - https://treehouse.org.za/ip )
new_ip6=$( ip -6 addr show ${iface} | grep global | grep -oP '(?<=inet6\s)[\da-f:]+' )
cur_ip4=$( nslookup -type=a ${host}.${zone} | grep -oP '(?<=^Address:\ )\d+(\.\d+){3}$' )
cur_ip6=$( nslookup -type=aaaa ${host}.${zone} | grep -oP '(?<=^Address:\ )[\da-f:]+$' )
if [ -z ${new_ip4} ] && [ -z ${new_ip6} ]; then
exit;
fi
if [ -z ${cache} ]; then
exit;
fi
if [ -f "${HOME}/${cache}" ]; then
old_ip4=$( cat "${HOME}/${cache}" | grep "\." )
old_ip6=$( cat "${HOME}/${cache}" | grep "\:" )
fi
if [ "${cur_ip4}" = "${new_ip4}" ] && [ "${new_ip4}" = "${old_ip4}" ] &&
[ "${cur_ip6}" = "${new_ip6}" ] && [ "${new_ip6}" = "${old_ip6}" ]; then
exit;
else
rm -f "${HOME}/${cache}"
fi
if [ -f "${HOME}/${cache}" ]; then
old_ip4=$( cat "${HOME}/${cache}" | grep "\." )
old_ip6=$( cat "${HOME}/${cache}" | grep "\:" )
fi
if [ "${cur_ip4}" = "${new_ip4}" ] && [ "${new_ip4}" = "${old_ip4}" ] &&
[ "${cur_ip6}" = "${new_ip6}" ] && [ "${new_ip6}" = "${old_ip6}" ]; then
exit;
else
rm -f "${HOME}/${cache}"
fi
ipv6_line=""
if [ -n "${new_ip6}" ]; then
ipv6_line="update add ${host}.${zone}. 60 AAAA ${new_ip6}"
fi
update=$( cat <<-EOF
server ${server}
zone ${zone}.
key ${host}.${zone} ${secret}
update delete ${host}.${zone}.
update add ${host}.${zone}. 60 A ${new_ip4}
${ipv6_line}
update add ${host}.${zone}. 60 TXT "Updated on $( date )"
send
EOF
)
if echo "${update}" | nsupdate ; then
echo "${new_ip4}" >> "${HOME}/${cache}"
echo "${new_ip6}" >> "${HOME}/${cache}"
else
echo "Request was:"
echo "${update}"
fi