Skip to content

Instantly share code, notes, and snippets.

@fengqi
Last active April 8, 2022 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fengqi/0d5979c1a15c678db2c260970f98183b to your computer and use it in GitHub Desktop.
Save fengqi/0d5979c1a15c678db2c260970f98183b to your computer and use it in GitHub Desktop.
ddns cloudflare
#!/bin/bash
set -e;
ipv4Regex="((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"
proxy="false"
# DSM Config
username="xx"
password="yy"
hostname="sub.domain.com"
ipAddr=`curl -s cip.cc|awk 'NR==1{print $3}'`
#ipAddr=`curl -s 'https://cloudflare.com/cdn-cgi/trace'|grep ip|awk -F '=' '{print $2}'`
if [[ $ipAddr =~ $ipv4Regex ]]; then
recordType="A";
else
recordType="AAAA";
fi
listDnsApi="https://api.cloudflare.com/client/v4/zones/${username}/dns_records?type=${recordType}&name=${hostname}"
createDnsApi="https://api.cloudflare.com/client/v4/zones/${username}/dns_records"
res=$(curl -s -X GET "$listDnsApi" -H "Authorization: Bearer $password" -H "Content-Type:application/json")
resSuccess=$(echo "$res" | jq -r ".success")
if [[ $resSuccess != "true" ]]; then
echo "badauth";
exit 1;
fi
recordIp=$(echo "$res" | jq -r ".result[0].content")
if [[ $recordIp = "$ipAddr" ]]; then
echo "nochg";
exit 0;
fi
recordId=$(echo "$res" | jq -r ".result[0].id")
if [[ $recordId = "null" ]]; then
# Record not exists
res=$(curl -s -X POST "$createDnsApi" -H "Authorization: Bearer $password" -H "Content-Type:application/json" --data "{\"type\":\"$recordType\",\"name\":\"$hostname\",\"content\":\"$ipAddr\",\"proxied\":$proxy}")
else
# Record exists
updateDnsApi="https://api.cloudflare.com/client/v4/zones/${username}/dns_records/${recordId}";
res=$(curl -s -X PUT "$updateDnsApi" -H "Authorization: Bearer $password" -H "Content-Type:application/json" --data "{\"type\":\"$recordType\",\"name\":\"$hostname\",\"content\":\"$ipAddr\",\"proxied\":$proxy}")
fi
resSuccess=$(echo "$res" | jq -r ".success")
if [[ $resSuccess = "true" ]]; then
echo "good";
else
echo "badauth";
fi
@0neday
Copy link

0neday commented Aug 31, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment