Skip to content

Instantly share code, notes, and snippets.

@dominik-hadl
Last active June 24, 2020 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dominik-hadl/f88df96cbfce3542d085 to your computer and use it in GitHub Desktop.
Save dominik-hadl/f88df96cbfce3542d085 to your computer and use it in GitHub Desktop.
DDNS manager script using CloudFlare. DDNS for free! :)
#!/bin/sh
# --------------------------------------
# CloudFlare DDNS Manager
# --------------------------------------
# This script checks if the WAN (public) IP address is different (eg. dynamic)
# and if it is, then updates the DNS record stored on CloudFlare.
#
# Uses curl to be compatible with machines that don't have wget by default (Mac OSX).
#
# Usage
# =====
# 1. Run './cf-ddns.sh'
#
# Optional
# ========
# Follow these steps to run this script every 5 minutes.
# 1. Run 'crontab -e'
# 2. Add this on a new line (modify):
# */5 * * * * /path/to/the/script/cf-ddns.sh >/dev/null 2>&1
#
# Authors
# =======
# * jfro (initial version)
# * Ross Hosman (modified to use curl and CloudFlare)
# * Dominik Hadl (new API, comments, reorganized)
#
# --------------------------------------
# Your CloudFlare API Token
cftkn="YOUR_API_TOKEN"
# Your CloudFlare account email
cfemail="YOUR_REGISTERED_EMAIL"
# The domain stored on CloudFlare you want to change
cfdomain="YOUR_CLOUDFLARE_MANAGED_DOMAIN"
# The subdomain, or record name of that domain
cfsubdomain="YOUR_CLOUDFLARE_MANAGED_SUBDOMAIN"
# The DNS record ID
#
# See this article for instructions on how the get the ID:
# https://www.cloudflare.com/docs/client-api.html#s3.3
#
cfzoneid="YOUR_CLOUDFLARE_DNS_RECORD_ID"
# --------------------------------------
# Get the WAN IP
WAN_IP=`curl -s ifconfig.me`
# Get the last saved WAN IP
if [ -f "$HOME/.cf-ddns/wan_ip.txt" ]; then
OLD_WAN_IP=`cat "$HOME/.cf-ddns/wan_ip.txt"`
else
echo "No file, need IP"
OLD_WAN_IP=""
if [ ! -d "$HOME/.cf-ddns" ]; then
mkdir "$HOME/.cf-ddns"
fi
fi
# Check if it has changed and update if needed
if [ "$WAN_IP" = "$OLD_WAN_IP" ]; then
echo "IP Unchanged"
else
echo $WAN_IP > "$HOME/.cf-ddns/wan_ip.txt"
echo "Updating DNS to $WAN_IP"
curl -s https://www.cloudflare.com/api_json.html \
-d "a=rec_edit" \
-d "tkn=$cftkn" \
-d "email=$cfemail" \
-d "z=$cfdomain" \
-d "name=$cfsubdomain" \
-d "service_mode=0" \
-d "ttl=1" \
-d "type=A" \
-d "id=$cfzoneid" \
-d "content=$WAN_IP" > /dev/null
fi
# --------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment