基于 DNSPod API 的 DDNS 脚本,长期自用稳定,在此简单记录一下;

本脚本来自https://github.com/yzeng1995/fast_set_centos
  1. 购买域名,例如:yourdomain.com;
  2. DNS服务器修改为DNSPod;
  3. 设置二级域名解析,例如将xxx.yourdomain.com解析到 8.8.8.8;
  4. 管理控制台中创建认证信息,获取ID和token;
  5. 修改下方Shell脚本中的idtokenDOMAINSUB_DOMAIN

    #!/bin/bash
    
    # This program establish ddns service
    # to modify the public ip address of dns server.
    # The dns server is dnspod.
    # /etc/crontab # if centos etc.
    # */10 * * * * root /usr/local/sbin/dnspod_ddns.sh 1>&2> /dev/null
    # /etc/crontabs/root # if openwrt etc.
    # */10 * * * * /usr/sbin/dnspod_ddns.sh
    
    #TOKEN=id,token
    TOKEN="112233,67fa231667a33de0f5255f62d33161eb"
    #full domain name
    DOMAIN="yourdomain.com"
    #sub domain first name
    SUB_DOMAIN="xxx"
    
    # TOKEN=`cat dnspod_ddns.conf|grep TOKEN|awk -F'=' '{print $2}'`
    # DOMAIN=`cat dnspod_ddns.conf|grep -e '^DOMAIN'|awk -F'=' '{print $2}'`
    # SUB_DOMAIN=`cat dnspod_ddns.conf|grep SUB_DOMAIN|awk -F'=' '{print $2}'`
    
    
    DATA="login_token=$TOKEN&format=json&domain=$DOMAIN&sub_domain=$SUB_DOMAIN&record_type=A&offset=0&length=3"
    JOSN_RECORDS=`curl -4 -s -X POST https://dnsapi.cn/Record.List -d $DATA`
    
    RECORD_ID=`echo $JOSN_RECORDS|sed '/id/ s/.*id":"\(.*\)","ttl.*/\1/'`
    LINE_ID=`echo $JOSN_RECORDS|sed '/line_id/ s/.*line_id":"\(.*\)","type.*/\1/'`
    #=================get record ip
    IP_RESOLVED=`echo $JOSN_RECORDS|sed '/value/ s/.*value":"\(.*\)","enabled.*/\1/'`
    
    #================get real ip
    #REAL_IP=`cat</dev/tcp/ns1.dnspod.net/6666`
    REAL_IP=`curl -4 -s  myip.ipip.net|awk -F' |:' '{print $3}'`
    
    #REAL_IP="2.2.3.2"
    if [ $REAL_IP != $IP_RESOLVED ]; then
            #================modify record
            DATA="login_token=$TOKEN&format=json&domain=$DOMAIN&record_id=$RECORD_ID&sub_domain=$SUB_DOMAIN&value=$REAL_IP&record_type=A&record_line_id=$LINE_ID"
            # echo $DATA
            JSON_RESULT=`curl -4 -s -X POST https://dnsapi.cn/Record.Modify -d $DATA`
            echo $JSON_RESULT >> /var/log/dnspod_ddns.log
            IP_RESOLVED=$REAL_IP
    fi
  6. 将程序添加到系统的定时任务中;

    # crontab -e
    # 每十分钟执行 /root/ddns.sh 脚本
    */10 *  *  *  * root /root/ddns.sh 1>&2> /dev/null
  7. 重启cron服务或直接重启生效;