txydns.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. # -*- coding: utf-8 -*-
  2. import sys
  3. import hmac
  4. import time
  5. import random
  6. import hashlib
  7. import binascii
  8. #第三方包,需要安装
  9. # python2:pip install requests
  10. # python3:pip3 install requests
  11. import requests
  12. # @akgnah https://github.com/akgnah
  13. class Client(object):
  14. def __init__(self, secret_id, secret_key, host, uri, **params):
  15. self.secret_id = secret_id
  16. self.secret_key = secret_key
  17. self.host = host
  18. self.uri = uri
  19. self.params = params
  20. if sys.version_info[0] > 2:
  21. self.Py3 = True
  22. self.secret_key = bytes(self.secret_key, 'utf-8')
  23. else:
  24. self.Py3 = False
  25. def public_params(self):
  26. params = {
  27. 'Nonce': random.randint(1, 9999),
  28. 'SecretId': self.secret_id,
  29. 'SignatureMethod': 'HmacSHA1',
  30. 'Timestamp': int(time.time()),
  31. }
  32. params.update(self.params)
  33. return params
  34. def sign(self, params, method='GET'):
  35. params = params.copy()
  36. params.update(self.public_params())
  37. p = {}
  38. for k in params:
  39. if method == 'POST' and str(params[k])[0:1] == '@':
  40. continue
  41. p[k.replace('_', '.')] = params[k]
  42. ps = '&'.join('%s=%s' % (k, p[k]) for k in sorted(p))
  43. msg = '%s%s%s?%s' % (method.upper(), self.host, self.uri, ps)
  44. if self.Py3:
  45. msg = bytes(msg, 'utf-8')
  46. hashed = hmac.new(self.secret_key, msg, hashlib.sha1)
  47. base64 = binascii.b2a_base64(hashed.digest())[:-1]
  48. if self.Py3:
  49. base64 = base64.decode()
  50. params['Signature'] = base64
  51. return params
  52. def send(self, params, method='GET'):
  53. params = self.sign(params, method)
  54. req_host = 'https://{}{}'.format(self.host, self.uri)
  55. if method == 'GET':
  56. resp = requests.get(req_host, params=params)
  57. else:
  58. resp = requests.post(req_host, data=params)
  59. return resp.json()
  60. # View details at https://cloud.tencent.com/document/product/302/4032
  61. class Cns:
  62. def __init__(self, secret_id, secret_key):
  63. host, uri = 'cns.api.qcloud.com', '/v2/index.php'
  64. self.client = Client(secret_id, secret_key, host, uri)
  65. def list(self, domain,subDomain):
  66. body = {
  67. 'Action': 'RecordList',
  68. 'domain': domain,
  69. 'subDomain': subDomain
  70. }
  71. return self.client.send(body)
  72. @staticmethod
  73. def getDomain(domain):
  74. domain_parts = domain.split('.')
  75. if len(domain_parts) > 2:
  76. rootdomain='.'.join(domain_parts[-(2 if domain_parts[-1] in {"co.jp","com.tw","net","com","com.cn","org","cn","gov","net.cn","io","top","me","int","edu","link"} else 3):])
  77. selfdomain=domain.split(rootdomain)[0]
  78. return (selfdomain[0:len(selfdomain)-1],rootdomain)
  79. return ("",domain)
  80. def create(self, domain, name, _type, value):
  81. body = {
  82. 'Action': 'RecordCreate',
  83. 'domain': domain,
  84. 'subDomain': name,
  85. 'recordType': _type,
  86. 'recordLine': '默认',
  87. 'value': value
  88. }
  89. return self.client.send(body)
  90. def delete(self, domain, _id):
  91. body = {
  92. 'Action': 'RecordDelete',
  93. 'domain': domain,
  94. 'recordId': _id
  95. }
  96. return self.client.send(body)
  97. if __name__ == '__main__':
  98. # Create your secret_id and secret_key at https://console.cloud.tencent.com/cam/capi
  99. _, option, domain, name, value,secret_id, secret_key = sys.argv # pylint: disable=all
  100. domain = Cns.getDomain(domain)
  101. if domain[0]=="":
  102. selfdomain = name
  103. else:
  104. selfdomain = name + "." + domain[0]
  105. cns = Cns(secret_id, secret_key)
  106. if option == 'add':
  107. result=(cns.create(domain[1], selfdomain, 'TXT', value))
  108. elif option == 'clean':
  109. for record in cns.list(domain[1],selfdomain)['data']['records']:
  110. #print (record['name'],record['id'] )
  111. result= (cns.delete(domain[1], record['id']))
  112. #print (result["message"])
  113. #print(result)