前言

此方法只针对域名的解析由cloudflare进行管理

可能有些服务器因为各种特殊原因经常会更换公网IP,这样会导致更换IP后原来解析的域名就无法访问了,要去手动修改解析记录到新的IP,比较麻烦

创建脚本

1.新建空白文件如:cfddns.sh

2.复制文章下面代码粘贴到文件,修改代码里面的API令牌/主域名/子域名三个位置,其他部分内容可默认不修改(API令牌脚本注释里面有说明在哪获取)

#!/usr/bin/env bash
set -o errexit
set -o nounset
#set -o pipefail

# Automatically update your CloudFlare DNS record to the IP, Dynamic DNS
# Can retrieve cloudflare Domain id and list zone's, because, lazy
# Sparkle version

# Place at:
# sudo wget https://raw.githubusercontent.com/zanjie1999/cloudflare-api-v4-ddns/master/cf-v4-ddns.sh -O /usr/local/bin/cf-ddns.sh
# sudo chmod +x /usr/local/bin/cf-ddns.sh
# sudo nano /usr/local/bin/cf-ddns.sh
# run `crontab -e` and add next line:
# */2 * * * * /usr/local/bin/cf-ddns.sh >/dev/null 2>&1
# or you need log:
# */2 * * * * /usr/local/bin/cf-ddns.sh >> /var/log/cf-ddns.log 2>&1


# Usage:
# cf-ddns.sh -k cloudflare-api-token \
#            -h host.example.com \     # fqdn of the record you want to update
#            -z example.com \          # will show you all zones if forgot, but you need this
#            -t A|AAAA                 # specify ipv4/ipv6, default: ipv4
#            -p cache file path        # default /$HOME/.cf

# Optional flags:
#            -f false|true \           # force dns update, disregard local stored ip

# default config

# API Token, see https://dash.cloudflare.com/profile/api-tokens,
# 填写API令牌,注意是API令牌,没有就通过上面链接创建一个,不是Global API Key
CFTOKEN=替换成你的api令牌

# Zone name, eg: example.com
# 你的主域名,dns必须在CloudFlare
CFZONE_NAME=改为你的主域名如abc.com

# Hostname to update, eg: homeserver.example.com or example.com
# 你要解析的子域名,需先在CloudFlare手动解析一条相同的A记录
CFRECORD_NAME=改为你的子域名如a.abc.com

# Record type, A(IPv4)|AAAA(IPv6), default IPv4
# 解析类型,默认A记录
CFRECORD_TYPE=A

# Cloudflare TTL for record, between 120 and 86400 seconds
# TTL值,填0为默认
CFTTL=0

# Ignore local file, update ip anyway
FORCE=false

CFFILE_PATH=/$HOME/.cf

WANIPSITE="http://v4.ipv6-test.com/api/myip.php"

NOW_DATE_TIME=$(date "+%Y-%m-%d %H:%M:%S")

# Site to retrieve WAN ip, other examples are: bot.whatismyipaddress.com, https://api.ipify.org/ ...
if [ "$CFRECORD_TYPE" = "A" ]; then
  :
elif [ "$CFRECORD_TYPE" = "AAAA" ]; then
  WANIPSITE="http://v6.ipv6-test.com/api/myip.php"
else
  echo "$NOW_DATE_TIME $CFRECORD_TYPE specified is invalid, CFRECORD_TYPE can only be A(for IPv4)|AAAA(for IPv6)"
  exit 2
fi

# get parameter
while getopts k:h:z:t:f:p: opts; do
  case ${opts} in
    k) CFTOKEN=${OPTARG} ;;
    h) CFRECORD_NAME=${OPTARG} ;;
    z) CFZONE_NAME=${OPTARG} ;;
    t) CFRECORD_TYPE=${OPTARG} ;;
    f) FORCE=${OPTARG} ;;
    p) CFFILE_PATH=${OPTARG} ;;
  esac
done

# mkdir if CFFILE_PATH not exist
if [ ! -d "$CFFILE_PATH" ];then
    mkdir -p $CFFILE_PATH
fi

# If required settings are missing just exit
if [ "$CFTOKEN" = "" ]; then
  echo "$NOW_DATE_TIME Missing api-key(API-Key缺少或不正确), 通过此链接进入创建: https://dash.cloudflare.com/profile/api-tokens"
#   echo "$NOW_DATE_TIME Missing api-key(API-Key缺少或不正确), get at: https://dash.cloudflare.com/profile/api-tokens"
  echo "$NOW_DATE_TIME and save in ${0} or using the -k flag"
  exit 2
fi

if [ "$CFRECORD_NAME" = "" ]; then
  echo "$NOW_DATE_TIME Missing hostname, what host do you want to update?"
  echo "$NOW_DATE_TIME save in ${0} or using the -h flag"
  exit 2
fi

# If the hostname is not a FQDN
if [ "$CFRECORD_NAME" != "$CFZONE_NAME" ] && ! [ -z "${CFRECORD_NAME##*$CFZONE_NAME}" ]; then
  CFRECORD_NAME="$CFRECORD_NAME.$CFZONE_NAME"
  echo "$NOW_DATE_TIME  => Hostname is not a FQDN, assuming $CFRECORD_NAME"
fi

# Get current and old WAN ip
WAN_IP=`curl -s ${WANIPSITE}`
WAN_IP_FILE=$CFFILE_PATH/.cf-wan_ip_$CFRECORD_NAME.txt
if [ -f $WAN_IP_FILE ]; then
  OLD_WAN_IP=`cat $WAN_IP_FILE`
else
  echo "$NOW_DATE_TIME No file, need IP"
  OLD_WAN_IP=""
fi

# If WAN IP is unchanged an not -f flag, exit here
if [ "$WAN_IP" = "$OLD_WAN_IP" ] && [ "$FORCE" = false ]; then
  echo "$NOW_DATE_TIME WAN IP Unchanged(IP没有变动), to update anyway use flag -f true"
  exit 0
fi

# Get zone_identifier & record_identifier
ID_FILE=$CFFILE_PATH/.cf-id_$CFRECORD_NAME.txt
if [ -f $ID_FILE ] && [ $(wc -l $ID_FILE | cut -d " " -f 1) == 4 ] \
  && [ "$(sed -n '3,1p' "$ID_FILE")" == "$CFZONE_NAME" ] \
  && [ "$(sed -n '4,1p' "$ID_FILE")" == "$CFRECORD_NAME" ]; then
    CFZONE_ID=$(sed -n '1,1p' "$ID_FILE")
    CFRECORD_ID=$(sed -n '2,1p' "$ID_FILE")
else
    echo "$NOW_DATE_TIME Updating zone_identifier & record_identifier"
    CFZONE_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$CFZONE_NAME" -H "Authorization: Bearer $CFTOKEN" -H "Content-Type: application/json" | grep -Po '(?<="id":")[^"]*' | head -1 )
    CFRECORD_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$CFZONE_ID/dns_records?name=$CFRECORD_NAME" -H "Authorization: Bearer $CFTOKEN" -H "Content-Type: application/json"  | grep -Po '(?<="id":")[^"]*' | head -1 )
    echo "$CFZONE_ID" > $ID_FILE
    echo "$CFRECORD_ID" >> $ID_FILE
    echo "$CFZONE_NAME" >> $ID_FILE
    echo "$CFRECORD_NAME" >> $ID_FILE
fi

# If WAN is changed, update cloudflare
echo "$NOW_DATE_TIME Updating DNS to $WAN_IP"

RESPONSE=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$CFZONE_ID/dns_records/$CFRECORD_ID" \
  -H "Authorization: Bearer $CFTOKEN" \
  -H "Content-Type: application/json" \
  --data "{\"id\":\"$CFZONE_ID\",\"type\":\"$CFRECORD_TYPE\",\"name\":\"$CFRECORD_NAME\",\"content\":\"$WAN_IP\", \"ttl\":$CFTTL}")

if [ "$RESPONSE" != "${RESPONSE%success*}" ] && [ "$(echo $RESPONSE | grep "\"success\":true")" != "" ]; then
  echo "$NOW_DATE_TIME Updated succesfuly!"
  echo "$WAN_IP" > $WAN_IP_FILE
  exit
else
  echo "$NOW_DATE_TIME Something went wrong :("
  echo "$NOW_DATE_TIME Response: $RESPONSE"
  exit 1
fi

脚本使用

在搭建了宝塔面板的服务器上使用
  1. 自行在宝塔面板将cfddns.sh脚本文件上传至指定目录,比如/www/shell
  2. 进入宝塔计划任务,任务类型:shell脚本,任务名称:自行设置如cfddns,执行周期:如每30分钟运行一次N分钟,30分钟
  3. 脚本内容根据刚才存放脚本的目录填入bash /www/shell/cf.sh
  4. 点击添加任务保持计划任务
在Linux服务器上使用
  1. 在终端使用命令或者winscp等软件将脚本上传至服务器指定目录,如/www/shell
  2. 编辑crontab

    1. 输入crontab -e(第一次使用可能会提示Select an editor. To change later, run 'select-editor',选择/usr/bin/vim.basic项目序号并按回车即可)
    2. 按下 a 键进入到编辑模式
    3. 输入*/30 * * * * /www/shell/cfddns.sh
    4. 同时按下ctrl+c 退出编辑模式
    5. 按下shift+: 输入wq退出 crontab
  3. cron表达式编写方法阅读此篇文章:
最后修改:2022 年 05 月 08 日
如果觉得我的文章对你有用,请随意赞赏