Created
February 21, 2025 04:17
-
-
Save Jiuh-star/6ed3d112ad27684000e11c17d770d50f to your computer and use it in GitHub Desktop.
IPv6 DDNS via 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
#!/usr/bin/env bash | |
# This script update IPv6 address to Cloudflare and send notification message via WxPusher. | |
# with `crontab -e` to set periodical task. | |
set -x | |
ZONE_ID={} | |
TOKEN_KEY={} | |
TARGET={} | |
WXTOKEN={} | |
WXUID={} | |
echo "DDNS BEGIN" | |
new_ipv6=$(/usr/sbin/ip -6 a | awk -F '[ \t]+|/' '/inet6/ && $3 != "::1" && $3 !~ /^fe80::/ && $3 !~ /^fda8:/ {ipv6=$3; getline; if ($2=="valid_lft") {split($3, t, "sec"); if (t[1] > max) {max=t[1]; best=ipv6}}} END {print best}') | |
records=$(curl https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records \ | |
-H "Authorization: Bearer $TOKEN_KEY" \ | |
-H 'Content-Type: application/json') | |
old_ipv6=$(echo $records | python3 -c "import sys, json; print([record for record in json.load(sys.stdin)['result'] if record['name'] == '$TARGET'][0]['content'])") | |
record_id=$(echo $records | python3 -c "import sys, json; print([record for record in json.load(sys.stdin)['result'] if record['name'] == '$TARGET'][0]['id'])") | |
if [ ! -z "$new_ipv6" ] && [ "$old_ipv6" != "$new_ipv6" ] | |
then | |
curl https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$record_id \ | |
-X PATCH \ | |
-H 'Content-Type: application/json' \ | |
-H "Authorization: Bearer $TOKEN_KEY" \ | |
-d "{\"content\": \"$new_ipv6\"}" | |
updates="DDNS: pi.jiuh.top --> $new_ipv6" | |
cmd=$(cat <<EOF | |
curl --request POST \ | |
-H "Content-type: application/json" \ | |
-d "{\"appToken\":\"$WXTOKEN\",\"content\":\"${updates}\",\"contentType\":1,\"uids\":[\"$WXUID\"]}" \ | |
https://wxpusher.zjiecode.com/api/send/message | |
EOF | |
) | |
echo $cmd | at 9:00 AM | |
fi | |
echo "DDNS END" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment