-
Notifications
You must be signed in to change notification settings - Fork 28
/
aliyun.py
138 lines (117 loc) · 4.38 KB
/
aliyun.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#!/usr/bin/env python
import sys
import time
import urllib
import base64
import hashlib
import hmac
import logging
import logging.handlers
if sys.version_info < (3,0):
import urllib2
import urllib
from base64 import encodestring as base64encode
else:
import urllib.request as urllib2
import urllib.parse as urllib
from base64 import encodebytes as base64encode
class AliyunDns:
__endpoint = 'http://alidns.aliyuncs.com'
__letsencryptSubDomain = '_acme-challenge'
__appid = ''
__appsecret = ''
__logger = logging.getLogger("logger")
def __init__(self, appid, appsecret):
self.__appid = appid
self.__appsecret = appsecret
def __getSignatureNonce(self):
return int(round(time.time() * 1000))
def __percentEncode(self, str):
if sys.version_info <(3,0):
res = urllib.quote(str.decode().encode('utf8'), '')
else:
res = urllib.quote(str.encode('utf8'))
res = res.replace('+', '%20')
res = res.replace('\'', '%27')
res = res.replace('\"', '%22')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
def __signature(self, params):
sortedParams = sorted(params.items(), key=lambda params: params[0])
query = ''
for (k, v) in sortedParams:
query += '&' + \
self.__percentEncode(k) + '=' + self.__percentEncode(str(v))
stringToSign = 'GET&%2F&' + self.__percentEncode(query[1:])
try:
if (sys.version_info <(3,0)):
h = hmac.new(self.__appsecret + "&", stringToSign, hashlib.sha1)
else:
h = hmac.new((self.__appsecret + "&").encode(encoding="utf-8"), stringToSign.encode(encoding="utf-8"), hashlib.sha1)
except Exception as e:
self.__logger.error(e)
signature = base64encode(h.digest()).strip()
return signature
def __request(self, params):
commonParams = {
'Format': 'JSON',
'Version': '2015-01-09',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': self.__getSignatureNonce(),
'SignatureVersion': '1.0',
'AccessKeyId': self.__appid,
'Timestamp': time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
}
# print(commonParams)
# merge all params
finalParams = commonParams.copy()
finalParams.update(params)
# signature
finalParams['Signature'] = self.__signature(finalParams)
self.__logger.info('Signature'+ str(finalParams['Signature']))
# get final url
url = '%s/?%s' % (self.__endpoint, urllib.urlencode(finalParams))
# print(url)
request = urllib2.Request(url)
try:
f = urllib2.urlopen(request)
response = f.read()
self.__logger.info(response.decode('utf-8'))
except urllib2.HTTPError as e:
self.__logger.info(e.read().strip().decode('utf-8'))
raise SystemExit(e)
def addDomainRecord(self, domain, rr, value):
params = {
'Action': 'AddDomainRecord',
'DomainName': domain,
'RR': rr,
'Type': 'TXT',
'Value': value
}
self.__request(params)
def deleteSubDomainRecord(self, domain, rr):
params = {
'Action': 'DeleteSubDomainRecords',
'DomainName': domain,
'RR': rr,
'Type': 'TXT'
}
self.__request(params)
def addLetsencryptDomainRecord(self, domain, value):
parts = domain.split('.')
ln = len(parts)
if ln > 2 and not domain.endswith(".cn"):
self.addDomainRecord(".".join(parts[ln - 2:ln]), self.__letsencryptSubDomain + '.' + ".".join(parts[0:ln - 2]), value)
else:
self.addDomainRecord(domain, self.__letsencryptSubDomain, value)
def deleteLetsencryptDomainRecord(self, domain):
parts = domain.split('.')
ln = len(parts)
if ln > 2 and not domain.endswith(".cn"):
self.deleteSubDomainRecord(".".join(parts[ln - 2:ln]), self.__letsencryptSubDomain + '.' + ".".join(parts[0:ln - 2]))
else:
self.deleteSubDomainRecord(domain, self.__letsencryptSubDomain)
def toString(self):
print('AliyunDns[appid='+self.__appid +
', appsecret='+self.__appsecret+']')