使用DNSPOD API动态更新域名DNS记录

之前买NAS时,弄好了aria2c迅雷离线下载和trasmisstion pt下载,甚是方便;没在家的时候,自动下载资源,要最大限度的使用ADSL资源啊!~

在路由器做一下端口映射,以便外网时,能够加任务,增加使用的便利性;由于电信的限制,一般80端口是被封锁了的,所以建议使用9000以上的端口.

另外,花生壳的动态域名体验不好,而且有些路由器都没有内置;因此,就是用dnspod免费DNS服务器吧~

下面就是具体步骤,当然,实现本功能的前提是自己要有一个域名:

NAS系统实际为一个嵌入式linux,支持python,因此先安装了官网的api: https://github.com/DNSPod/dnspod-python

获取路由器IP,访问: http://devzc.com/app/getip.php 即可(当然也可以使用其他网站的,我这里为了简单,就直接用本博客的脚本啦);

ddns.py源码:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from dnspod.apicn import *
#from apicn import *
import time

ISOTIMEFORMAT="%Y-%m-%d %X"

def gettime():
return time.strftime( ISOTIMEFORMAT, time.localtime() )

def http_getip():
conn = httplib.HTTPSConnection("devzc.com")
headers = {"Accept": "text/html", "User-Agent": "dnspod-python/0.01 (im@chuangbo.li; DNSPod.CN API v2.8)"}
conn.request("GET", "/app/getip.php","", headers)

response = conn.getresponse()
data = response.read()
conn.close()
return data.strip()

def main():
email = "test@qq.com"
password = "test"
domain_name = "test.com"
sub_domain = "nas"

print gettime()
print "DomainList"
api = DomainList(email=email, password=password)
domains = api().get("domains")
domain_id=0

for domain in domains:
if domain.get("name") == domain_name:
domain_id=int(domain.get("id"))
if domain_id < 0:
print "error to get %s domain's info!"%domain_name
os.sys.exit(-1)

print "RecordList:%d"%domain_id
api = RecordList(domain_id, email=email, password=password)
records = api().get("records")
record_id = 0
for record in records:
if record.get("name") == sub_domain:
record_id=int(record.get("id"))

if record_id < 0:
print "error to get %s domain sub-domain: %s's info!"%domain_name%sub_domain
os.sys.exit(-1)

print "RecordModify:%d"%record_id
wan_ip=http_getip()
print "wan_ip:%s"%wan_ip
# api = RecordCreate("w123", "A", u'默认'.encode("utf8"), '1.1.1.1', 600, domain_id=domain_id, email=email, password=password)
# print api().get("record", {})
api = RecordModify(record_id,sub_domain, "A", u'默认'.encode("utf8"), wan_ip, 600, domain_id=domain_id, email=email, password=password)
print api().get("record", {})

if __name__ == '__main__':
main()

 

然后将下面的脚本加入到crontab即可,我这里是设置了每半个小时更新一次,看大家具体需求了~
*/30 * * * * python /root/ddns.py >> /mnt/disk1/Downloads/ddns.log 2>&1

已有1条评论

  1. 点子 2013-12-30 17:16 回复
    这个不错,

    优选网 <a href="http://www.youxuanw.com" rel="nofollow">www.youxuanw.com</a>
| 1个评论