贴一下自用的CloudXNS DDNS 脚本

CloudXNS 是国内这几家提供 DDNS 服务里面,使用差不多是最简单的了,还没有什么限制,这里贴一下自用的 CloudXNS DDNS 脚本供大家参考,配合 crontab 完美实现动态 DDNS。

#!/bin/sh

DOMAIN="hk.feeeei.com"


API_KEY="这里需要填写 CloudXNS 提供的 API_KEY"
SECRET_KEY="这里需要填写 CloudXNS 提供的 SECRET_KEY"


current_ip=""
dns_ip=""

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

log(){
    echo "[${now_time}] $1"
}

get_current_ip(){
    current_ip=$(curl -s https://api.ip.sb/ip)
    log "Now ip is: $current_ip"
}

get_dns_ip(){
dns_ip=$(host $DOMAIN|grep " has address "|cut -d" " -f4)
    log "Dns ip is: $dns_ip"
}

compare_ip(){
    if [ "$current_ip" == "$dns_ip" ];then
        log "Ip same in dns,skip update"
        exit
    fi
}

update_dns_ip(){
    api_url="http://www.cloudxns.net/api2/ddns"
    data="{\"domain\":\"$DOMAIN\",\"ip\":\"${current_ip}\"}"
    time=$(date -R)
    hmac=$(echo -n $API_KEY$api_url$data$time$SECRET_KEY | md5sum | awk '{print $1}')
    header1="API-KEY:"$API_KEY
    header2="API-REQUEST-DATE:"$time
    header3="API-HMAC:"$hmac
    header4="API-FORMAT:json"

    result=$(curl -s -k -X POST -H $header1 -H "$header2" -H $header3 -H $header4 -d "$data" $api_url)

    if  [[ $(echo $result | grep "success") != "" ]] ;then
        log "[${now_time}] Update ${DOMAIN} ${current_ip} successful"
    else
        log "[${now_time}] Error: ${result}"
    fi
}

get_current_ip
get_dns_ip
compare_ip
update_dns_ip

保存之后,在 crontab 中添加如下任务

*/5 * * * * /root/cloudxns_ddns.sh >> /var/log/cloudxns_ddns.log

每5分钟更新尝试更新一次 ddns,并且将结果重定向到 /var/log/cloudxns_ddns.log 中。

Last modification:October 24th, 2018 at 12:17 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment