Skip to content

Instantly share code, notes, and snippets.

@hlwanghl
Created May 25, 2016 00:40
Show Gist options
  • Save hlwanghl/fa82ff80fdd6689120034fd8dc7f0b1d to your computer and use it in GitHub Desktop.
Save hlwanghl/fa82ff80fdd6689120034fd8dc7f0b1d to your computer and use it in GitHub Desktop.
A DDNS Bash script to refresh DNSPod.cn record according to always changing public IP.
#!/bin/bash
validateIp() {
oldIFS=$IFS
IFS=.
set -- $1
IFS=${oldIFS}
# Ensure there are 4 parts.
[[ "$#" -ne "4" ]] && exit 1
for oct in $1 $2 $3 $4; do
# Ensure \'${oct}\' is not NaN.
[[ ${oct} =~ ^[0-9]+$ ]] || exit 1
# Ensure \'${oct}\' is within [0, 255].
[[ "${oct}" -lt "0" || "${oct}" -gt "255" ]] && exit 1
done
}
source ~/.ddns
echo Retrieving current IP...
currentIp=$(curl -s ${IP_SERVICE})
if [ "$?" -ne "0" ]; then
echo Something wrong when retrieving dynamic IP. Exiting now and will try again later.
exit 1
fi
echo Current IP is ${currentIp}.
validateIp ${currentIp}
declare lastIp
if [ -f ${LOG_PATH} ]; then
echo Retrieving last IP from log...
lastIp=$(tail -1 ${LOG_PATH}|awk '{print $2}')
else
echo Retrieving last IP from DNS record...
# lastIp=$(host ${SUB_DOMAIN}.${DOMAIN}|awk '{print $4}')
fi
echo Last IP record is ${lastIp}.
[ "${currentIp}" == "${lastIp}" ] && echo IP unchanged. && exit 0
echo Updating DDNS record...
# curl -X POST https://dnsapi.cn/Record.Ddns -d "login_token=${LOGIN_ID},${LOGIN_TOKEN}&format=json&domain_id=${DOMAIN_ID}&record_id=${RECORD}&record_line=默认&sub_domain=${SUB_DOMAIN}"
echo Saving to log...
if [ "$?" -eq "0" ];then
currentTime=$(date -Ins)
echo "${currentTime} ${currentIp}" >> ${LOG_PATH}
else
echo Error occurred.
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment