树莓派Python+Aliyun API 50行代码实现阿里云域名ddns

准备工作:
1.下载aliyun-openapi-python-sdk-master 手动安装aliyunsdkcore、aliyunsdkalidns,其他的包暂时不需要可以不安装
2.登陆阿里云获取Accesskey
备注:
1.代码很精简只有50行,只是为了实现自己得需求(对比当前ip和阿里云上的域名解析记录判断是否更新解析),没有额外的功能,为需要的朋友做个参考。

import json
import urllib
from aliyunsdkcore import client
from aliyunsdkalidns.request.v20150109 import UpdateDomainRecordRequest
from aliyunsdkalidns.request.v20150109 import DescribeDomainRecordsRequest

AccessKeyID = 'your access key id'
AccessKeySecret = 'your access key secret'
mydomain = 'your domain'

def get_ip(): #获取ip
    retry_times = 3
    url = "http://ip.chinaz.com/getip.aspx"
    i = 0
    ip = ''
    while i < retry_times:
        try:
            r = urllib.request.urlopen(url).read()
            r = r.decode(encoding='utf-8')
            r = r.replace('ip', '"ip"').replace('address', '"address"').replace("'", '"')
            r = json.loads(r)
            ip = r['ip']
            break
        except Exception as e:
            i = i + 1
    return ip

def get_records(): #获取解析记录
    myclient = client.AcsClient(ak=AccessKeyID, secret=AccessKeySecret)
    request = DescribeDomainRecordsRequest.DescribeDomainRecordsRequest()
    request.set_DomainName(mydomain)
    request.set_accept_format('json')
    result = myclient.do_action_with_exception(request)
    result = json.loads(result.decode())
    return result['DomainRecords']['Record']

def update_record(record, ip): #更新解析记录
    myclient = client.AcsClient(ak=AccessKeyID, secret=AccessKeySecret)
    request = UpdateDomainRecordRequest.UpdateDomainRecordRequest()
    request.set_RR(record['RR'])
    request.set_Type(record['Type'])
    request.set_RecordId(record['RecordId'])
    request.set_Value(ip)
    request.set_accept_format('json')
    myclient.do_action_with_exception(request)

def main(): #对比当前ip和解析记录中得ip判断是否更新解析
    ip = get_ip()
    records = get_records()
    for record in records:
        if ip != record['Value'] and len(ip) > 0:
            update_record(record, ip)

if __name__ == '__main__':
    main()

你可能感兴趣的:(树莓派Python+Aliyun API 50行代码实现阿里云域名ddns)