DDNS

ddns

脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/bin/bash

# 根据实际修改以下字段值
auth_email="user@example.com" # CloudFlare 注册邮箱
auth_key="c2547eb745079dac9320b638f5e225cf483cc5cfdda41" # API Key
zone_name="example.com" # 要做指向的根域名
record_name="www.example.com" # 要做指向的记录

# 根据需要修改
ip=$(curl -s http://ipv4.icanhazip.com) # 获取外网 IP
ip_file="ip.txt" # IP 自动检测记录
id_file="cloudflare.ids" # CloudFlare 验证文件
log_file="cloudflare.log" # CloudFlare API 执行日志

# 日志格式
log() {
if [ "$1" ]; then
echo -e "[$(date)] - $1" >> $log_file
fi
}

# 检测
log "Check Initiated"

if [ -f $ip_file ]; then
old_ip=$(cat $ip_file)
if [ $ip == $old_ip ]; then
echo "IP has not changed."
exit 0
fi
fi

if [ -f $id_file ] && [ $(wc -l $id_file | cut -d " " -f 1) == 2 ]; then
zone_identifier=$(head -1 $id_file)
record_identifier=$(tail -1 $id_file)
else
zone_identifier=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$zone_name" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" -H "Content-Type: application/json" | grep -Po '(?<="id":")[^"]*' | head -1 )
record_identifier=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$zone_identifier/dns_records?name=$record_name" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" -H "Content-Type: application/json" | grep -Po '(?<="id":")[^"]*')
echo "$zone_identifier" > $id_file
echo "$record_identifier" >> $id_file
fi

update=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$zone_identifier/dns_records/$record_identifier" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" -H "Content-Type: application/json" --data "{\"id\":\"$zone_identifier\",\"type\":\"A\",\"name\":\"$record_name\",\"content\":\"$ip\"}")

if [[ $update == *"\"success\":false"* ]]; then
message="API UPDATE FAILED. DUMPING RESULTS:\n$update"
log "$message"
echo -e "$message"
exit 1
else
message="IP changed to: $ip"
echo "$ip" > $ip_file
log "$message"
echo "$message"
fi

定期执行

比如上述脚本保存到 /root/ddns.sh,先增加执行权限

1
# chmod +x /root/ddns.sh   

手动单次执行:

1
# bash ddns.sh

利用 Crontab 任务定期指定:

1
# crontab -e

键盘上敲 i 进入编辑,添加如下字段:

1
*/5 * * * * bash /root/ddns.sh

这段代码的意思是每 5 分钟执行一次检测。

其他说明

CloudFlare 获取 API

登录后(未注册托管域名请先注册托管),在右上角找到 My Profile,点击进入并下拉到最底部,就可以看到 APIs Key 了,我们需要的是 Global API Key