Last active
August 29, 2015 14:01
-
-
Save joshenders/64b4a5277d839321a653 to your computer and use it in GitHub Desktop.
afraid.org DDNS updater
This file contains hidden or 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 | |
# Cron every 10 minutes: | |
# 0,10,20,30,40,50 * * * * /usr/local/sbin/ddns-update | |
# | |
# For logging: | |
# $ mkdir /var/log/ddns-update | |
# $ cat << EOF > /etc/logrotate.d/ddns-update | |
# /var/log/ddns-update.log { | |
# rotate 3 | |
# monthly | |
# compress | |
# missingok | |
# } | |
# EOF | |
PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' | |
basename="$(basename $0)" | |
serviceURL='http://icanhazip.com' | |
updateURL='https://freedns.afraid.org/dynamic/update.php?YOUR_SECRET_TOKEN' | |
database="/etc/default/${basename}" | |
log="/var/log/${basename}/${basename}.log" | |
timestamp="$(date --rfc-3339=seconds | tr -d '\n')" | |
function update_ip() { | |
# usage: update_ip "url" | |
local url="$1" | |
curl --silent "${url}" | |
return 0 | |
} | |
function update_database() { | |
# usage: update_database "file" "ip" | |
local file="$1" | |
local ip="$2" | |
echo "STORED_IP='${ip}'" > "${file}" | |
return 0 | |
} | |
function get_current_ip() { | |
# usage: get_current_ip "service" | |
local service="$1" | |
local response="$(curl --silent ${service})" | |
local pattern='^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | |
# set CURRENT_IP global | |
if [[ "${response}" =~ $pattern ]]; then | |
CURRENT_IP="${response}" | |
fi | |
return 0 | |
} | |
# get $STORED_IP | |
if [[ -f "${database}" ]]; then | |
source "${database}" | |
fi | |
# get $CURRENT_IP | |
get_current_ip "${serviceURL}" | |
# set new IP if it changed | |
if [[ "${STORED_IP}" != "${CURRENT_IP}" ]]; then | |
update_ip "${updateURL}" >> "${timestamp} ${log}" | |
update_database "${database}" "${CURRENT_IP}" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment