Raspberry Pi使用DNSPOD动态解析搭建web服务

把域名托管到DNSPOD,因为DNSPOD有动态API接口,还有Python脚本例子可以直接在Raspberry Pi上直接运行,这里使用了动态域名解析的功能。

DNSPOD 接口地址:

• https://dnsapi.cn/Record.Ddns

提交方法:

• POST

提交参数:

• 公共参数
• domainid 域名ID
• recordid 记录ID
• subdomain – 主机记录, 如 www
• recordline 记录线路,通过API记录线路获得,中文,比如:默认

获得domain_id可以用curl

curl -k https://dnsapi.cn/Domain.List -d "login_email=xxx&login_password=xxx"

获得record_id

curl -k https://dnsapi.cn/Record.List -d "login_email=xxx&login_password=xxx&domain_id=xxx"

官网有一个“动态域名解析脚本for Linux”的Python版本。 地址:https://gist.github.com/chuangbo/833369
P.S. 官网的脚本貌似返回ip那个地方有问题,后来参考了imxfeng的脚本,如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
 
import httplib, urllib
import socket
import time
import json
 
params = dict(
    login_email="[email protected]", # replace with your email
    login_password="pwd", # replace with your password
    format="json",
    domain_id=xxxxxx, # replace with your domain_od, can get it by API Domain.List
    record_id=xxxxxx, # replace with your record_id, can get it by API Record.List
    sub_domain="pi", # replace with your sub_domain
    record_line="默认",
)
current_ip = None
 
def ddns(ip):
    params.update(dict(value=ip))
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/json"}
    conn = httplib.HTTPSConnection("dnsapi.cn")
    conn.request("POST", "/Record.Ddns", urllib.urlencode(params), headers)
 
    response = conn.getresponse()
    print response.status, response.reason
    data = response.read()
    print data
    conn.close()
    return response.status == 200
 
def getip():
    url='http://ip.taobao.com/service/getIpInfo.php?ip=myip'
    page=urllib.urlopen(url)
    data=page.read()
    jsondata=json.loads(data)
    ip = jsondata['data']['ip']
    return ip
 
if __name__ == '__main__':
    while True:
        try:
            ip = getip()
            print ip
            if current_ip != ip:
                if ddns(ip):
                    current_ip = ip
        except Exception, e:
            print e
            pass
        time.sleep(30)

设置pi开机的时候自动运行这个脚本 ,在/etc/rc.local中加入一行

/usr/bin/python /root/dnspod.py




标签:none