99 lines
2.6 KiB
Bash
Executable File
99 lines
2.6 KiB
Bash
Executable File
#!/bin/sh
|
|
|
|
ping -qc 1 "${server}" > /dev/null
|
|
if [ ${?} != 0 ]; then
|
|
# We are offline
|
|
exit
|
|
fi
|
|
|
|
cache=.update_ip.cache
|
|
server=ns1.example.com
|
|
zone=dyn.example.com
|
|
host=desktop
|
|
secret=""
|
|
|
|
server_ip=$( dig +short ${server} | grep [0-9] | head -1 )
|
|
iface=$( ip route get ${server_ip} | grep -Po '(?<=(dev ))(\S+)' )
|
|
|
|
# TODO trigger not via cron, but using ip monitor in a while/sleep loop:
|
|
#ip monitor address dev ${iface} | while read event; do
|
|
# case "$event" in
|
|
# 'Deleted default'*)
|
|
# ...
|
|
# ;;
|
|
# 'local '*)
|
|
# ...
|
|
# ;;
|
|
# ...)
|
|
# ...
|
|
# ;;
|
|
# ...
|
|
# esac
|
|
#done
|
|
|
|
# This has to be retrieved externally
|
|
new_ip4=$( wget -4 -q -O - https://treehouse.org.za/ip )
|
|
# If the iface call fails, we will get several interfaces, so pipe through head to get the first (default) interface
|
|
new_ip6=$( ip -6 addr show ${iface} scope global | grep -vE '(mngtmpaddr|deprecated)' | grep -oP '(?<=inet6\s)[\da-f:]+' | grep -vE '^fc' | head -1 )
|
|
|
|
cur_ip4=$( nslookup -type=a ${host}.${zone} | grep -oP '(?<=^Address:\ )\d+(\.\d+){3}$' | head -1 )
|
|
cur_ip6=$( nslookup -type=aaaa ${host}.${zone} | grep -oP '(?<=^Address:\ )[\da-f:]+$' | head -1 )
|
|
|
|
#if [ -z ${new_ip4} ] && [ -z ${new_ip6} ]; then
|
|
if [ -z ${new_ip4} ]; 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}" ] && [ "${cur_ip6}" != "${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
|