如果想要2台VPS通过cname 轮换接替工作。
可以参考下面sh脚本。
模拟环境:
18:01时 tva.123456.xyz和tvb.1123456.xyz cname 到 vps1.nice.com
01:01时 tva.123456.xyz和tvb.1123456.xyz cname 到 vps2.nice.com1 18 * * * bash /root/pixman-cf-cname.sh
1 1 * * * bash /root/pixman-cf-cname.sh
#!/usr/bin/env bash
# 设置 Cloudflare API 凭证
CFKEY="6xxxxac0d你的CFKEYxxx4"
CFUSER="你的CF邮箱@gmail.com"
CFZONE_NAME="123456.xyz"
# 定义切换的记录
RECORD1="tva.123456.xyz"
RECORD2="tvb.1123456.xyz"
# 设置 CNAME 值
CNAME_NIGHT="vps1.nice.com"
CNAME_DAY="vps2.nice.com"
# 获取 Cloudflare Zone ID
CFZONE_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$CFZONE_NAME" \
-H "X-Auth-Email: $CFUSER" \
-H "X-Auth-Key: $CFKEY" \
-H "Content-Type: application/json" | grep -Po '(?<="id":")[^"]*' | head -1)
# 获取当前时间
HOUR=$(date +'%H')
# 根据时间设置目标CNAME
if [ "$HOUR" -ge 18 ] || [ "$HOUR" -lt 1 ]; then
TARGET_CNAME=$CNAME_NIGHT
else
TARGET_CNAME=$CNAME_DAY
fi
# 定义更新DNS记录的函数
update_cname_record() {
local RECORD_NAME=$1
local TARGET=$2
# 获取DNS记录ID
CFRECORD_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$CFZONE_ID/dns_records?name=$RECORD_NAME" \
-H "X-Auth-Email: $CFUSER" \
-H "X-Auth-Key: $CFKEY" \
-H "Content-Type: application/json" | grep -Po '(?<="id":")[^"]*' | head -1)
# 更新DNS记录
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$CFZONE_ID/dns_records/$CFRECORD_ID" \
-H "X-Auth-Email: $CFUSER" \
-H "X-Auth-Key: $CFKEY" \
-H "Content-Type: application/json" \
--data "{\"type\":\"CNAME\",\"name\":\"$RECORD_NAME\",\"content\":\"$TARGET\",\"ttl\":120}"
}
# 更新记录
update_cname_record $RECORD1 $TARGET_CNAME
update_cname_record $RECORD2 $TARGET_CNAME
echo "DNS records updated to $TARGET_CNAME for $RECORD1 and $RECORD2."