Skip to content

Instantly share code, notes, and snippets.

@jim60105
Last active December 7, 2023 13:35
Show Gist options
  • Save jim60105/27c49665bc81f74c381e8b79bbe27f4f to your computer and use it in GitHub Desktop.
Save jim60105/27c49665bc81f74c381e8b79bbe27f4f to your computer and use it in GitHub Desktop.
Cloudflare DDNS bash,以cron於主機排程執行
#!/bin/sh
### GPLv3
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
### HOW TO
# How to get zone id: https://api.cloudflare.com/#zone-list-zones
# curl -X GET "https://api.cloudflare.com/client/v4/zones" \
# -H "X-Auth-Email: EMAIL" \
# -H "X-Auth-Key: GLOBAL_API_KEY"
# How to get dns_records id: https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
# curl -X GET "https://api.cloudflare.com/client/v4/zones/ZONE_ID/dns_records/" \
# -H "X-Auth-Email: EMAIL" \
# -H "X-Auth-Key: GLOBAL_API_KEY"
### Parameters
EMAIL="a@gmail.com"
ZONE_ID="123123123asdfasdfasdf"
GLOBAL_API_KEY="123123123asdfasdfasdf"
A_RECORD_NAME="xx.example.com"
A_RECORD_ID="123123123asdfasdfasdf"
AAAA_RECORD_NAME="xx.example.com"
AAAA_RECORD_ID="123123123asdfasdfasdf"
### IPv4 A Record
NEW_IP=$(curl -s https://api.ipify.org)
echo $NEW_IP
CURRENT_IP=$(cat current_ip.txt)
if [ "$NEW_IP" = "$CURRENT_IP" ]; then
echo "No Change in IP Adddress"
else
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${A_RECORD_ID}" \
-H "X-Auth-Email: ${EMAIL}" \
-H "X-Auth-Key: ${GLOBAL_API_KEY}" \
-H "Content-Type: application/json" \
--data '{"type":"A","name":"'$A_RECORD_NAME'","content":"'$NEW_IP'","proxied":false}' >/dev/null
echo $NEW_IP >current_ip.txt
fi
### IPv6 AAAA Record
NEW_IP_6=$(curl -s https://api6.ipify.org)
echo $NEW_IP_6
CURRENT_IP_6=$(cat current_ipv6.txt)
if [ "$NEW_IP_6" = "$CURRENT_IP_6" ]; then
echo "No Change in IPv6 Adddress"
else
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${AAAA_RECORD_ID}" \
-H "X-Auth-Email: ${EMAIL}" \
-H "X-Auth-Key: ${GLOBAL_API_KEY}" \
-H "Content-Type: application/json" \
--data '{"type":"AAAA","name":"'$AAAA_RECORD_NAME'","content":"'$NEW_IP_6'","proxied":false}' >/dev/null
echo $NEW_IP_6 >current_ipv6.txt
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment