Python平台下调用阿里云API参数实现DDNS功能


注:经过查阅大量网页,汇总出Python平台下调用阿里云API参数实现DDNS功能,此功能可以直接替换掉向日葵(Oray)的DDNS服务。

Python平台下调用阿里云API参数实现DDNS功能

(本文前提是在阿里云购有域名)


1.安装Python 2.7(略)、阿里云api的python sdk

下载pip    http://download.csdn.net/tag/get-pip.py 

pip2.7 install aliyun-python-sdk-corepip2.7 install aliyun-python-sdk-alidns

2.Python下安装pip,在get-pip.py目录下运行

python get-pip.py

或者直接用 yum install python-pip -y


3.在阿里云开启Access Key管理

记录下Access Key ID Access Key Secret


4.将以下内容标红部分修改为自己的API,保存到记事本中,改名为UpgradeDNS.py

#coding:utf-8
from aliyunsdkcore import client
from aliyunsdkalidns.request.v20150109 import DescribeDomainsRequest,DescribeDomainRecordsRequest,UpdateDomainRecordRequest
import json,urllib,re
#替换以下参数
ID="LTA***********"
Secret="1xsU*****************"
RegionId="cn-hangzhou"
DomainName="y****en.cn"
#想要自动修改的主机名和域名类型
HostNameList = ["*"]
Types = "A"
clt = client.AcsClient(ID,Secret,RegionId)
#获取公网ip
def GetLocalIP():
    IPInfo = urllib.urlopen("http://ip.chinaz.com/getip.aspx").read()
    IP = re.findall(r"ip:'(.*?)',", IPInfo)[0]
    return IP
#获取域名列表(暂时无用)
def GetDomainList():
    DomainList = DescribeDomainsRequest.DescribeDomainsRequest()
    DomainList.set_accept_format('json')
    DNSListJson = json.loads(clt.do_action_with_exception(DomainList))
    print DNSListJson
#更新域名ip
def EditDomainRecord(HostName, RecordId, Types, IP):
    UpdateDomainRecord = UpdateDomainRecordRequest.UpdateDomainRecordRequest()
    UpdateDomainRecord.set_accept_format('json')
    UpdateDomainRecord.set_RecordId(RecordId)
    UpdateDomainRecord.set_RR(HostName)
    UpdateDomainRecord.set_Type(Types)
    UpdateDomainRecord.set_TTL('600')
    UpdateDomainRecord.set_Value(IP)
    UpdateDomainRecordJson = json.loads(clt.do_action_with_exception(UpdateDomainRecord))
    print UpdateDomainRecordJson
#获取域名信息
def GetAllDomainRecords(DomainName, Types, IP):
    DomainRecords = DescribeDomainRecordsRequest.DescribeDomainRecordsRequest()
    DomainRecords.set_accept_format('json')
    DomainRecords.set_DomainName(DomainName)
    DomainRecordsJson = json.loads(clt.do_action_with_exception(DomainRecords))
    for HostName in HostNameList:
        for x in DomainRecordsJson['DomainRecords']['Record']:
            RR = x['RR']
            Type = x['Type']
            if RR == HostName and Type == Types:
                RecordId = x['RecordId']
                print RecordId
                EditDomainRecord(HostName, RecordId, Types, IP)
IP = GetLocalIP()
GetDomainList()
GetAllDomainRecords(DomainName, Types, IP)

4.在Python下执行py代码

python UpgradeDNS.py

5.在服务器上通过 corntab 设置一项定时计划,让服务器定期执行该脚本。 linux 设置定时计划命令:

crontab -e




 


你可能感兴趣的:(Python平台下调用阿里云API参数实现DDNS功能)