-
-
Save fengqi/0d5979c1a15c678db2c260970f98183b to your computer and use it in GitHub Desktop.
ddns cloudflare
This file contains 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 | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/benkulbertis/fff10759c2391b6618dd#gistcomment-3878052
use sed instead jq