实现域名解析
- 查询子域名记录
- 添加解析记录
- 更新已有记录
类似的接口只要各种参数传入也能轻松实现
#! /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新手