Skip to content

Commit

Permalink
add TTL config
Browse files Browse the repository at this point in the history
  • Loading branch information
ddgth committed Dec 25, 2020
1 parent 1459d53 commit 36a1141
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 69 deletions.
11 changes: 7 additions & 4 deletions cf2dns.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
#DNS服务商 如果使用DNSPod改为1 如果使用阿里云解析改成2
DNS_SERVER = 1

#解析生效时间,默认为600秒 如果不是DNS付费版用户 不要修改!!!
TTL = 600

#API 密钥
#腾讯云后台获取 https://console.cloud.tencent.com/cam/capi
#阿里云后台获取 https://help.aliyun.com/document_detail/53045.html?spm=a2c4g.11186623.2.11.2c6a2fbdh13O53 注意需要添加DNS控制权限 AliyunDNSFullAccess
Expand Down Expand Up @@ -72,7 +75,7 @@ def changeDNS(line, s_info, c_info, domain, sub_domain, cloud):
cf_ip = c_info.pop(random.randint(0,len(c_info)-1))["ip"]
if cf_ip in str(s_info):
continue
ret = cloud.change_record(domain, info["recordId"], sub_domain, cf_ip, "A", line)
ret = cloud.change_record(domain, info["recordId"], sub_domain, cf_ip, "A", line, TTL)
if(DNS_SERVER != 1 or ret["code"] == 0):
log_cf2dns.logger.info("CHANGE DNS SUCCESS: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+line+"----RECORDID: " + str(info["recordId"]) + "----VALUE: " + cf_ip )
else:
Expand All @@ -84,7 +87,7 @@ def changeDNS(line, s_info, c_info, domain, sub_domain, cloud):
cf_ip = c_info.pop(random.randint(0,len(c_info)-1))["ip"]
if cf_ip in str(s_info):
continue
ret = cloud.create_record(domain, sub_domain, cf_ip, "A", line)
ret = cloud.create_record(domain, sub_domain, cf_ip, "A", line, TTL)
if(DNS_SERVER != 1 or ret["code"] == 0):
log_cf2dns.logger.info("CREATE DNS SUCCESS: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+line+"----VALUE: " + cf_ip )
else:
Expand All @@ -97,7 +100,7 @@ def changeDNS(line, s_info, c_info, domain, sub_domain, cloud):
if cf_ip in str(s_info):
create_num += 1
continue
ret = cloud.change_record(domain, info["recordId"], sub_domain, cf_ip, "A", line)
ret = cloud.change_record(domain, info["recordId"], sub_domain, cf_ip, "A", line, TTL)
if(DNS_SERVER != 1 or ret["code"] == 0):
log_cf2dns.logger.info("CHANGE DNS SUCCESS: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+line+"----RECORDID: " + str(info["recordId"]) + "----VALUE: " + cf_ip )
else:
Expand Down Expand Up @@ -134,7 +137,7 @@ def main(cloud):
log_cf2dns.logger.error("DELETE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+record["line"] + "----MESSAGE: " + retMsg["message"] )
ret = cloud.get_record(domain, 100, sub_domain, "A")
if DNS_SERVER != 1 or ret["code"] == 0 :
if DNS_SERVER != 1 or ("Free" in ret["data"]["domain"]["grade"] and AFFECT_NUM > 2):
if DNS_SERVER == 1 and "Free" in ret["data"]["domain"]["grade"] and AFFECT_NUM > 2:
AFFECT_NUM = 2
cm_info = []
cu_info = []
Expand Down
99 changes: 40 additions & 59 deletions cf2dns_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import urllib.parse
import urllib3
import os
from dns.qCloud import QcloudApi
from dns.aliyun import AliApi

#可以从https://shop.hostmonit.com获取
KEY = os.environ["KEY"] #"o1zrmHAF"
Expand All @@ -22,46 +24,12 @@
SECRETKEY = os.environ["SECRETKEY"] #'ZrVs*************gqjOp1zVl'
#默认为普通版本 不用修改
AFFECT_NUM = 2

#DNS服务商 如果使用DNSPod改为1 如果使用阿里云解析改成2
DNS_SERVER = 1
#解析生效时间,默认为600秒 如果不是DNS付费版用户 不要修改!!!
TTL = 600

urllib3.disable_warnings()
class QcloudApi():
def __init__(self):
self.SecretId = SECRETID
self.secretKey = SECRETKEY

def get(self, module, action, **params):
config = {
'Action': action,
'Nonce': random.randint(10000, 99999),
'SecretId': self.SecretId,
'SignatureMethod': 'HmacSHA256',
'Timestamp': int(time.time()),
}
url_base = '{0}.api.qcloud.com/v2/index.php?'.format(module)

params_all = dict(config, **params)

params_sorted = sorted(params_all.items(), key=operator.itemgetter(0))

srcStr = 'GET{0}'.format(url_base) + ''.join("%s=%s&" % (k, v) for k, v in dict(params_sorted).items())[:-1]
signStr = base64.b64encode(hmac.new(bytes(self.secretKey, encoding='utf-8'), bytes(srcStr, encoding='utf-8'), digestmod=hashlib.sha256).digest()).decode('utf-8')

config['Signature'] = signStr

params_last = dict(config, **params)

params_url = urllib.parse.urlencode(params_last)

url = 'https://{0}&'.format(url_base) + params_url
http = urllib3.PoolManager()
r = http.request('GET', url=url, retries=False)
ret = json.loads(r.data.decode('utf-8'))
if ret.get('code', {}) == 0:
return ret
else:
raise Exception(ret)


def get_optimization_ip():
try:
Expand All @@ -75,7 +43,7 @@ def get_optimization_ip():
print(e)
return None

def changeDNS(line, s_info, c_info, domain, sub_domain, qcloud):
def changeDNS(line, s_info, c_info, domain, sub_domain, cloud):
global AFFECT_NUM
if line == "CM":
line = "移动"
Expand All @@ -92,44 +60,44 @@ def changeDNS(line, s_info, c_info, domain, sub_domain, qcloud):
for info in s_info:
if len(c_info) == 0:
break
cf_ip = c_info.pop(0)["ip"]
cf_ip = c_info.pop(random.randint(0,len(c_info)-1))["ip"]
if cf_ip in str(s_info):
continue
ret = qcloud.get(module='cns', action='RecordModify', domain=domain, recordId=info["recordId"], subDomain=sub_domain, value=cf_ip, recordType='A', recordLine=line)
if(ret["code"] == 0):
ret = cloud.change_record(domain, info["recordId"], sub_domain, cf_ip, "A", line, TTL)
if(DNS_SERVER != 1 or ret["code"] == 0):
print("CHANGE DNS SUCCESS: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+line+"----RECORDID: " + str(info["recordId"]) + "----VALUE: " + cf_ip )
else:
print("CHANGE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+line+"----RECORDID: " + str(info["recordId"]) + "----VALUE: " + cf_ip + "----MESSAGE: " + ret["message"] )
elif create_num > 0:
for i in range(create_num):
if len(c_info) == 0:
break
cf_ip = c_info.pop(0)["ip"]
cf_ip = c_info.pop(random.randint(0,len(c_info)-1))["ip"]
if cf_ip in str(s_info):
continue
ret = qcloud.get(module='cns', action='RecordCreate', domain=domain, subDomain=sub_domain, value=cf_ip, recordType='A', recordLine=line)
if(ret["code"] == 0):
ret = cloud.create_record(domain, sub_domain, cf_ip, "A", line, TTL)
if(DNS_SERVER != 1 or ret["code"] == 0):
print("CREATE DNS SUCCESS: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+line+"----VALUE: " + cf_ip )
else:
print("CHANGE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+line+"----RECORDID: " + str(info["recordId"]) + "----VALUE: " + cf_ip + "----MESSAGE: " + ret["message"] )
print("CREATE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+line+"----RECORDID: " + str(info["recordId"]) + "----VALUE: " + cf_ip + "----MESSAGE: " + ret["message"] )
else:
for info in s_info:
if create_num == 0 or len(c_info) == 0:
break
cf_ip = c_info.pop(0)["ip"]
cf_ip = c_info.pop(random.randint(0,len(c_info)-1))["ip"]
if cf_ip in str(s_info):
create_num += 1
continue
ret = qcloud.get(module='cns', action='RecordModify', domain=domain, recordId=info["recordId"], subDomain=sub_domain, value=cf_ip, recordType='A', recordLine=line)
if(ret["code"] == 0):
ret = cloud.change_record(domain, info["recordId"], sub_domain, cf_ip, "A", line, TTL)
if(DNS_SERVER != 1 or ret["code"] == 0):
print("CHANGE DNS SUCCESS: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+line+"----RECORDID: " + str(info["recordId"]) + "----VALUE: " + cf_ip )
else:
print("CHANGE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+line+"----RECORDID: " + str(info["recordId"]) + "----VALUE: " + cf_ip + "----MESSAGE: " + ret["message"] )
create_num += 1
except Exception as e:
print("CHANGE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(e))
log_cf2dns.logger.error("CHANGE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(e))

def main(qcloud):
def main(cloud):
global AFFECT_NUM
if len(DOMAINS) > 0:
try:
Expand All @@ -145,9 +113,19 @@ def main(qcloud):
temp_cf_cmips = cf_cmips.copy()
temp_cf_cuips = cf_cuips.copy()
temp_cf_ctips = cf_ctips.copy()
ret = qcloud.get(module='cns', action='RecordList', domain=domain, length=100, subDomain=sub_domain, recordType="A")
if ret["code"] == 0:
if "Free" in ret["data"]["domain"]["grade"] and AFFECT_NUM > 2:
if DNS_SERVER == 1:
ret = cloud.get_record(domain, 10, sub_domain, "CNAME")
if ret["code"] == 0:
for record in ret["data"]["records"]:
if record["line"] != "默认":
retMsg = cloud.del_record(domain, record["id"])
if(retMsg["code"] == 0):
print("DELETE DNS SUCCESS: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+record["line"] )
else:
print("DELETE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+record["line"] + "----MESSAGE: " + retMsg["message"] )
ret = cloud.get_record(domain, 100, sub_domain, "A")
if DNS_SERVER != 1 or ret["code"] == 0 :
if DNS_SERVER == 1 and "Free" in ret["data"]["domain"]["grade"] and AFFECT_NUM > 2:
AFFECT_NUM = 2
cm_info = []
cu_info = []
Expand All @@ -170,14 +148,17 @@ def main(qcloud):
ct_info.append(info)
for line in lines:
if line == "CM":
changeDNS("CM", cm_info, temp_cf_cmips, domain, sub_domain, qcloud)
changeDNS("CM", cm_info, temp_cf_cmips, domain, sub_domain, cloud)
elif line == "CU":
changeDNS("CU", cu_info, temp_cf_cuips, domain, sub_domain, qcloud)
changeDNS("CU", cu_info, temp_cf_cuips, domain, sub_domain, cloud)
elif line == "CT":
changeDNS("CT", ct_info, temp_cf_ctips, domain, sub_domain, qcloud)
changeDNS("CT", ct_info, temp_cf_ctips, domain, sub_domain, cloud)
except Exception as e:
print("CHANGE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(e))

if __name__ == '__main__':
qcloud = QcloudApi()
main(qcloud)
if DNS_SERVER == 1:
cloud = QcloudApi(SECRETID, SECRETKEY)
elif DNS_SERVER == 2:
cloud = AliApi(SECRETID, SECRETKEY)
main(cloud)
6 changes: 4 additions & 2 deletions dns/aliyun.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def get_record(self, domain, length, sub_domain, record_type):
result = json.JSONDecoder().decode(result)
return result

def create_record(self, domain, sub_domain, value, record_type, line):
def create_record(self, domain, sub_domain, value, record_type, line, ttl):
clt = client.AcsClient(self.access_key_id, self.access_key_secret, 'cn-hangzhou')
request = AddDomainRecordRequest.AddDomainRecordRequest()
request.set_DomainName(domain)
Expand All @@ -51,12 +51,13 @@ def create_record(self, domain, sub_domain, value, record_type, line):
request.set_Line(line)
request.set_Type(record_type)
request.set_Value(value)
request.set_TTL(ttl)
request.set_accept_format(rc_format)
result = clt.do_action(request).decode('utf-8')
result = json.JSONDecoder().decode(result)
return result

def change_record(self, domain, record_id, sub_domain, value, record_type, line):
def change_record(self, domain, record_id, sub_domain, value, record_type, line, ttl):
clt = client.AcsClient(self.access_key_id, self.access_key_secret, 'cn-hangzhou')
request = UpdateDomainRecordRequest.UpdateDomainRecordRequest()
request.set_RR(sub_domain)
Expand All @@ -70,6 +71,7 @@ def change_record(self, domain, record_id, sub_domain, value, record_type, line)
request.set_Line(line)
request.set_Type(record_type)
request.set_Value(value)
request.set_TTL(ttl)
request.set_accept_format(rc_format)
result = clt.do_action(request).decode('utf-8')
result = json.JSONDecoder().decode(result)
Expand Down
8 changes: 4 additions & 4 deletions dns/qCloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ def del_record(self, domain, record):
def get_record(self, domain, length, sub_domain, record_type):
return self.get(module = 'cns', action = 'RecordList', domain = domain, length = length, subDomain = sub_domain, recordType = record_type)

def create_record(self, domain, sub_domain, value, record_type, line):
return self.get(module = 'cns', action = 'RecordCreate', domain = domain, subDomain = sub_domain, value = value, recordType = record_type, recordLine = line)
def create_record(self, domain, sub_domain, value, record_type, line, ttl):
return self.get(module = 'cns', action = 'RecordCreate', domain = domain, subDomain = sub_domain, value = value, recordType = record_type, recordLine = line, ttl = ttl)

def change_record(self, domain, record_id, sub_domain, value, record_type, line):
return self.get(module = 'cns', action = 'RecordModify', domain = domain, recordId =record_id, subDomain = sub_domain, value = value, recordType = record_type, recordLine = line)
def change_record(self, domain, record_id, sub_domain, value, record_type, line, ttl):
return self.get(module = 'cns', action = 'RecordModify', domain = domain, recordId =record_id, subDomain = sub_domain, value = value, recordType = record_type, recordLine = line, ttl = ttl)

0 comments on commit 36a1141

Please sign in to comment.