阿里云域名云解析

实现域名解析

  • 查询子域名记录
  • 添加解析记录
  • 更新已有记录

类似的接口只要各种参数传入也能轻松实现

#! /usr/bin/env python
# -*- coding:utf-8 -*-
import urllib
import urllib2
import time
import json
import random
import hmac
import hashlib
import sys
import uuid
from copy import deepcopy
from base64 import encodestring as b64_encode_bytes

coding='utf-8'
AccessKeyId="xxxx"
AccessKeySecret="xxxxxxx" + "&"

class NwsSender:
    def init(self):
        self.url='https://alidns.aliyuncs.com/'
        self.timeout=10
    def send_data(self,data,op):
        try:
            req=urllib2.Request(self.url + "?" + data)
            timeout=self.timeout
            http_ret=urllib2.urlopen(req, timeout = timeout)
            response=http_ret.read()
            try:
                json_resp = json.loads(response)
                if op > 0:
                    print "send succ,op:%s,response:%s" % (op,response)
                    return response
                else:
                    totalcount = json_resp["TotalCount"]
                    if totalcount<=0:
                        print "send succ,totalcount:%s" % totalcount
                    else:
                        print "send succ,totalcount:%s,response:%s" % (totalcount,response)
                        return response
            except KeyError,e:
                print 'KeyError :%s, response:%s' % (str(e),response)
        except urllib2.URLError,e:
            print "send error:%s data:%s" % (str(e),data)

def ArgsCheck(args):
    if len(args) < 2 :
        Usage();
        return False
    else:
        return True

def Usage():
    print('Usage:');
    print('   create_recrode_domain subDomain ip')
	
def FmtParam(val):
    return urllib.quote(val.encode(coding), '-_.~')

def SortParams(dataDict):
    arr = []
    for k in dataDict:
        arr.append(k)
    arr.sort()
    text=""
    for k in arr:
        if text == "":
            text="%s=%s" % (FmtParam(k), FmtParam(dataDict[k]))
        else:
            text="%s&%s=%s" % (text, FmtParam(k), FmtParam(dataDict[k]))
    return text

def CreateSignature(text):
    h = hmac.new(AccessKeySecret,text,hashlib.sha1)
    Signature = b64_encode_bytes(h.digest()).strip()
    return Signature
	
def QuerySubDomainRecordList(commonData, SubDomain):
    data=deepcopy(commonData)
    data['Action']="DescribeSubDomainRecords"
    data['SubDomain']=SubDomain
    data['Type']='A'
    text="GET&"+FmtParam('/')+"&"+FmtParam(SortParams(data))
    data['Signature']=CreateSignature(text)
    return data

def RecordCreate(commonData, rr, ip):
    data=deepcopy(commonData)
    data['Action']="AddDomainRecord"
    data['RR']=rr
    data['Type']='A'
    data['Value']=ip
    text="GET&"+FmtParam('/')+"&"+FmtParam(SortParams(data))
    data['Signature']=CreateSignature(text)
    return data

def UpdateRecord(commonData, rr, ip, recordId):
    data=deepcopy(commonData)
    data['Action']="UpdateDomainRecord"
    data['RecordId']=recordId
    data['RR']=rr
    data['Type']='A'
    data['Value']=ip
    text="GET&"+FmtParam('/')+"&"+FmtParam(SortParams(data))
    data['Signature']=CreateSignature(text)
    return data

def main(argv):
    if ArgsCheck(argv)==False:
        return
    commonData={
        "AccessKeyId":AccessKeyId,
        "Version":'2015-01-09',
        "DomainName":'xxxx.com',
		"Format":'JSON',
    }
    ts=int(time.time())
    UUID=uuid.uuid1()
    utctimestr=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ts))
    commonData['Timestamp']=utctimestr
    commonData['SignatureNonce']=str(UUID)
    commonData['SignatureVersion']='1.0'
    commonData['SignatureMethod']='HMAC-SHA1'
    action=argv[1]
    subDomain=argv[2]
    rr=subDomain
    subDomain=subDomain+'.xxxx.com'
    sender=NwsSender()
    sender.init()
    if action=="query":
        data=QuerySubDomainRecordList(commonData, subDomain)
        xx = urllib.urlencode(data)
        response=sender.send_data(xx,0)
        if response:
            json_resp=json.loads(response)
            records=json_resp["DomainRecords"]["Record"]
            if len(records)>0:
                record=records[0]
                print "RR:%s, DomainName:%s, ip:%s" % (record["RR"], record["DomainName"], record["Value"])
            else:
                print "not exist record"
    elif action=="add":
        ip=argv[3]
        data=QuerySubDomainRecordList(commonData, subDomain)
        xx = urllib.urlencode(data)
        response=sender.send_data(xx,0)
        isAdd=True
        while True:
            if response is None:
                break
            json_resp=json.loads(response)
            records=json_resp["DomainRecords"]["Record"]
            if len(records)<=0:
                break
            record=records[0]
            if record["Value"]==ip:
                print "send succ, record exist"
                return
            isAdd=False
            data=UpdateRecord(commonData, rr, ip, record["RecordId"])
            xx = urllib.urlencode(data)
            response=sender.send_data(xx,1)
            if response:
                print "send succ, UpdateRecord response:%s" % response
            break
        if isAdd:
            data=RecordCreate(commonData, rr, ip)
            xx = urllib.urlencode(data)
            response=sender.send_data(xx,1)
            if response:
               print "send succ"


if __name__=='__main__':
    main(sys.argv)

ps:python新手

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值