diff --git a/README.md b/README.md
index cff3084..8a1c575 100644
--- a/README.md
+++ b/README.md
@@ -8,14 +8,21 @@
★ 本工具主要是将网站域名动态解析到获取到的优选ip上,目前支持阿里云DNS、DNSPod、华为云DNS、NameSilo
-### VPS789.com提供CF优选IP接口
-1、支持对CF优选IP的三网实时监测延迟、丢包率,支持查看24小时、一个月的监测数据。
+
-2、支持对CF优选IP的下载速度进行测试
+### CF优选IP接口(VPS789.com提供)
-3、基于CloudFlareST工具生成一个优选IP池,vps789的优选IP每天定时淘汰1/3网络不好的IP,从优选IP池补充到vps789中继续监测。通过持续补充优选IP和IP优胜略汰机制,保证vps789上的IP都是优中选优。
+**CF优选IP机制说明:**
-4、vps789优选IP监控页面地址:https://vps789.com/cfip
+基于CloudFlareST工具生成一个[初选IP池],vps789固定24小时监测200-500个IP。每天根据网络情况综合评估,淘汰1/3网络较差的IP,然后从[初选IP池]补充到vps789中继续监测。**通过持续补充优选IP和IP优胜略汰机制,保证vps789上的IP都是优中选优。**
+
+2、支持对cloudFlare IP进行延迟、丢包率、下载速度、晚高峰网络状态等多个维度的筛选
+
+3、vps789优选IP监控页面地址:https://vps789.com/cfip
+
+4、VPS789优选IP动态获取接口:https://vps789.com/public/sum/cfIpApi
+
+
### 使用方法
@@ -27,9 +34,7 @@
pip install -r requirements.txt
```
-1. 登录DNS解析平台,获取 SecretId、SecretKey。
- 如果使用阿里云DNS,注意需要添加DNS控制权限**AliyunDNSFullAccess**
- 如果使用NameSilo只用填SecretKey即可。
+1. 登录DNS解析平台,获取 SecretId、SecretKey。如果使用NameSilo只用填SecretKey即可。
2. 将脚本下载到本地修改start.py中的SecretId、SecretKey
@@ -39,8 +44,16 @@ pip install -r requirements.txt
4. 运行程序,如果能够正常运行可以选择cron定时执行(建议1个小时执行一次)
```python
-python start.py
+#域名解析在阿里云DNS
+python cfipToAliDns.py
+#域名解析在DnsPod
+python cfipToDnsPod.py
+#域名解析在华为云DNS
+python cfipToHwDns.py
+#域名解析在NameSilo
+python cfipToNameSilo.py
```
+
### 鸣谢
感谢以下项目提供技术支撑与实现思路
diff --git a/cfipToAliDns.py b/cfipToAliDns.py
new file mode 100644
index 0000000..df3f1fb
--- /dev/null
+++ b/cfipToAliDns.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import random
+import time
+import requests
+from dns.aliyun import AliApi
+from dns.core import Core
+from log import Logger
+import traceback
+
+
+#CM:移动 CU:联通 CT:电信 AB:境外 DEF:默认
+#需要动态解析到Cf优选ip的域名和子域名
+DOMAINS = {
+ "vps789.com": {"@": ["CM","CU","CT"],"www": ["CM","CU","CT"]},
+ "vpsxxx777.com": {"@": ["CM","CU","CT"]}
+}
+
+#解析生效条数
+AFFECT_NUM = 2
+
+#如果使用阿里云解析 REGION出现错误再修改 默认不需要修改 https://help.aliyun.com/document_detail/198326.html
+REGION_ALI = 'cn-hongkong'
+
+#解析生效时间,默认为600秒
+TTL = 600
+
+#阿里云后台获取 https://help.aliyun.com/document_detail/53045.html 注意需要添加DNS控制权限 AliyunDNSFullAccess
+SECRETID = 'LTAIxxxxxxxxxxxxxxxxxxxWcRDH'
+SECRETKEY = 'LOitxxxxxxxxxxxxxxxxxxxzcGR'
+
+if __name__ == '__main__':
+ config = {'DOMAINS':DOMAINS,"AFFECT_NUM":AFFECT_NUM,"TTL":TTL,"DNS_SERVER":2}
+ cloud = AliApi(SECRETID, SECRETKEY,REGION_ALI)
+ core = Core(cloud,config)
+ core.main()
+
\ No newline at end of file
diff --git a/cfipToDnsPod.py b/cfipToDnsPod.py
new file mode 100644
index 0000000..fc18909
--- /dev/null
+++ b/cfipToDnsPod.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import random
+import time
+import requests
+from dns.qCloud import QcloudApiv3 # QcloudApiv3 DNSPod 的 API 更新了 By github@z0z0r4
+from dns.core import Core
+from log import Logger
+import traceback
+
+
+#CM:移动 CU:联通 CT:电信 AB:境外 DEF:默认
+#需要动态解析到Cf优选ip的域名和子域名
+DOMAINS = {
+ "vps789.com": {"@": ["CM","CU","CT"],"www": ["CM","CU","CT"]},
+ "vpsxxx777.com": {"@": ["CM","CU","CT"]}
+}
+
+#解析生效条数
+#免费的DNSPod相同线路最多支持2条解析
+AFFECT_NUM = 2
+
+#解析生效时间,默认为600秒 如果不是DNS付费版用户 不要修改!!!
+TTL = 600
+
+#腾讯云后台获取 https://console.cloud.tencent.com/cam/capi
+SECRETID = 'LTAI5txxxxxxxxxxxxxxxxxcRDH'
+SECRETKEY = 'LOixxxxxxxxxxxxxxxxx4mzcGR'
+
+if __name__ == '__main__':
+ config = {'DOMAINS':DOMAINS,"AFFECT_NUM":AFFECT_NUM,"TTL":TTL,"DNS_SERVER":1}
+ cloud = QcloudApiv3(SECRETID, SECRETKEY)
+ core = Core(cloud,config)
+ core.main()
\ No newline at end of file
diff --git a/cfipToHwDns.py b/cfipToHwDns.py
new file mode 100644
index 0000000..245cac4
--- /dev/null
+++ b/cfipToHwDns.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import random
+import time
+import requests
+from dns.huawei import HuaWeiApi
+from dns.core import Core
+from log import Logger
+import traceback
+
+
+#CM:移动 CU:联通 CT:电信 AB:境外 DEF:默认
+#需要动态解析到Cf优选ip的域名和子域名
+DOMAINS = {
+ "vps789.com": {"@": ["CM","CU","CT"],"www": ["CM","CU","CT"]},
+ "vpsxxx777.com": {"@": ["CM","CU","CT"]}
+}
+
+#解析生效条数
+AFFECT_NUM = 2
+
+#如果使用华为云解析 需要从API凭证-项目列表中获取
+REGION_HW = 'cn-east-3'
+
+#解析生效时间,默认为600秒
+TTL = 600
+
+#华为云后台获取 https://support.huaweicloud.com/devg-apisign/api-sign-provide-aksk.html
+SECRETID = 'LTxxxxxxxxxxxxxxWcRDH'
+SECRETKEY = 'LOitxxxxxxxxxxxxxxxxxxmzcGR'
+
+if __name__ == '__main__':
+ config = {'DOMAINS':DOMAINS,"AFFECT_NUM":AFFECT_NUM,"TTL":TTL,"DNS_SERVER":3}
+ cloud = HuaWeiApi(SECRETID, SECRETKEY, REGION_HW)
+ core = Core(cloud,config)
+ core.main()
diff --git a/cfipToNameSilo.py b/cfipToNameSilo.py
new file mode 100644
index 0000000..0b6729f
--- /dev/null
+++ b/cfipToNameSilo.py
@@ -0,0 +1,32 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import random
+import time
+import requests
+from dns.nameSilo import NameSiloClient
+from dns.core import Core
+from log import Logger
+import traceback
+
+
+#CM:移动 CU:联通 CT:电信 AB:境外 DEF:默认
+#需要动态解析到Cf优选ip的域名和子域名#NameSilo不支持多线解析,只能选DEF默认线路
+DOMAINS = {
+ "vps789.com": {"@": ["DEF"],"www":["DEF"]},
+ "vpsxxx777.com": {"@": ["DEF"]},
+}
+
+#解析生效条数
+AFFECT_NUM = 2
+
+#解析生效时间,NameSilo最少为3600
+TTL = 3600
+
+#NameSilo后台获取 https://www.namesilo.com/account/api-manager NameSilo只用填SECRETKEY即可
+SECRETKEY = '72xxxxxxxxxxxxa332'
+
+if __name__ == '__main__':
+ config = {'DOMAINS':DOMAINS,"AFFECT_NUM":AFFECT_NUM,"TTL":TTL,"DNS_SERVER":4}
+ cloud = NameSiloClient(SECRETKEY)
+ core = Core(cloud,config)
+ core.main()
\ No newline at end of file
diff --git a/dns/core.py b/dns/core.py
new file mode 100644
index 0000000..7b6b91b
--- /dev/null
+++ b/dns/core.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import random
+import time
+import requests
+from dns.qCloud import QcloudApiv3 # QcloudApiv3 DNSPod 的 API 更新了 By github@z0z0r4
+from dns.aliyun import AliApi
+from dns.huawei import HuaWeiApi
+from dns.nameSilo import NameSiloClient
+from log import Logger
+import traceback
+
+class Core():
+
+ log_cf2dns = Logger('cf2dns.log', level='debug')
+
+ def __init__(self, cloud,config):
+ self.cloud = cloud
+ self.config = config
+
+ def get_optimization_ip(self):
+ try:
+ headers = headers = {'Content-Type': 'application/json'}
+ data = {}
+ response = requests.post('https://vps789.com/public/sum/cfIpApi', json=data, headers=headers)
+ if response.status_code == 200:
+ self.log_cf2dns.logger.info("GET OPTIMIZATION IP SUCCESS" )
+ return response.json()
+ else:
+ self.log_cf2dns.logger.error("GET OPTIMIZATION IP ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: REQUEST STATUS CODE IS NOT 200")
+ return None
+ except Exception as e:
+ self.log_cf2dns.logger.error("GETs OPTIMIZATION IP ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(e))
+ return None
+
+ #s_info已存在的ip,c_info 最新的优选cfip
+ def changeDNS(self,line, s_info, c_info, domain, sub_domain):
+ recordType = "A"
+
+ lines = {"CM": "移动", "CU": "联通", "CT": "电信", "AB": "境外", "DEF": "默认"}
+ line = lines[line]
+ print(s_info)
+ print(c_info)
+ try:
+ create_num = self.config['AFFECT_NUM'] - len(s_info)
+ # 如果线路能解析的ip已满,就用cfip一个一个去替换原来的ip解析
+ if create_num == 0:
+ for info in s_info:
+ if len(c_info) == 0:
+ break
+ cf_ip = c_info.pop(random.randint(0,len(c_info)-1))["ip"]
+ if cf_ip in str(s_info):
+ continue
+ ret = self.cloud.change_record(domain, info["recordId"], sub_domain, cf_ip, recordType, line, self.config['TTL'])
+ if(self.config['DNS_SERVER'] != 1 or ret["code"] == 0):
+ self.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:
+ self.log_cf2dns.logger.error("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"] )
+ # 如果线路还可以解析更多的ip,就添加cfip解析,直到用完
+ elif create_num > 0:
+ for i in range(create_num):
+ if len(c_info) == 0:
+ break
+ cf_ip = c_info.pop(random.randint(0,len(c_info)-1))["ip"]
+ if cf_ip in str(s_info):
+ continue
+ ret = self.cloud.create_record(domain, sub_domain, cf_ip, recordType, line, self.config['TTL'])
+ if(self.config['DNS_SERVER'] != 1 or ret["code"] == 0):
+ self.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:
+ self.log_cf2dns.logger.error("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"] )
+ # 如果线路能解析的ip已超出配额,就用cfip一个一个去替换原来的ip解析
+ else:
+ for info in s_info:
+ if create_num == 0 or len(c_info) == 0:
+ break
+ 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 = self.cloud.change_record(domain, info["recordId"], sub_domain, cf_ip, recordType, line, self.config['TTL'])
+ if(self.config['DNS_SERVER'] != 1 or ret["code"] == 0):
+ self.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:
+ self.log_cf2dns.logger.error("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:
+ self.log_cf2dns.logger.error("CHANGE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(e))
+
+ def main(self):
+
+ recordType = "A"
+ if len(self.config['DOMAINS']) > 0:
+ try:
+ cfips = self.get_optimization_ip()
+ if cfips == None or cfips["code"] != 0:
+ self.log_cf2dns.logger.error("GET CLOUDFLARE IP ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(cfips["data"]))
+ return
+ cf_cmips = cfips["data"]["CM"]
+ cf_cuips = cfips["data"]["CU"]
+ cf_ctips = cfips["data"]["CT"]
+ cf_defips = cfips["data"]["AllAvg"]
+ for domain, sub_domains in self.config['DOMAINS'].items():
+ for sub_domain, lines in sub_domains.items():
+ if self.config['DNS_SERVER'] == 4 and len(lines)!=1:
+ self.log_cf2dns.logger.info("域名解析为NameSilo时,线路只能填DEF")
+ return
+
+ #下面5个数组存的是不同线路最新获取的优选IP列表
+ temp_cf_cmips = cf_cmips.copy()
+ temp_cf_cuips = cf_cuips.copy()
+ temp_cf_ctips = cf_ctips.copy()
+ temp_cf_abips = cf_ctips.copy()
+ temp_cf_defips = cf_defips.copy()
+ if self.config['DNS_SERVER'] == 1:
+ ret = self.cloud.get_record(domain, 20, sub_domain, "CNAME")
+ if ret["code"] == 0:
+ for record in ret["data"]["records"]:
+ if record["line"] == "移动" or record["line"] == "联通" or record["line"] == "电信":
+ retMsg = self.cloud.del_record(domain, record["id"])
+ if(retMsg["code"] == 0):
+ self.log_cf2dns.logger.info("DELETE DNS SUCCESS: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+record["line"] )
+ else:
+ self.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 = self.cloud.get_record(domain, 100, sub_domain, recordType)
+ # ret["code"] == 0 就是self.config['DNS_SERVER'] == 1
+ if self.config['DNS_SERVER'] != 1 or ret["code"] == 0 :
+ if self.config['DNS_SERVER'] == 1 and "Free" in ret["data"]["domain"]["grade"] and self.config['AFFECT_NUM'] > 2:
+ self.config['AFFECT_NUM'] = 2
+ #下面5个数组存的是已存在的DNS解析列表
+ cm_info = []
+ cu_info = []
+ ct_info = []
+ ab_info = []
+ def_info = []
+ for record in ret["data"]["records"]:
+ info = {}
+ info["recordId"] = record["id"]
+ info["value"] = record["value"]
+ if record["line"] == "移动":
+ cm_info.append(info)
+ elif record["line"] == "联通":
+ cu_info.append(info)
+ elif record["line"] == "电信":
+ ct_info.append(info)
+ elif record["line"] == "境外":
+ ab_info.append(info)
+ elif record["line"] == "默认":
+ def_info.append(info)
+ for line in lines:
+ if line == "CM":
+ self.changeDNS("CM", cm_info, temp_cf_cmips, domain, sub_domain)
+ elif line == "CU":
+ self.changeDNS("CU", cu_info, temp_cf_cuips, domain, sub_domain)
+ elif line == "CT":
+ self.changeDNS("CT", ct_info, temp_cf_ctips, domain, sub_domain)
+ elif line == "AB":
+ self.changeDNS("AB", ab_info, temp_cf_abips, domain, sub_domain)
+ elif line == "DEF":
+ self.changeDNS("DEF", def_info, temp_cf_defips, domain, sub_domain)
+ except Exception as e:
+ traceback.print_exc()
+ self.log_cf2dns.logger.error("CHANGE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(e))
\ No newline at end of file
diff --git a/dns/nameSilo.py b/dns/nameSilo.py
index cb631c0..1ab39fb 100644
--- a/dns/nameSilo.py
+++ b/dns/nameSilo.py
@@ -20,6 +20,8 @@ class NameSiloClient:
response = requests.get(url)
response_body = response.json()
if response.status_code == 200:
+ if response_body["reply"]["code"] !=300:
+ raise Exception('namesilo接口错误:'+response_body["reply"]["detail"])
res={}
res["code"]=0
res["data"]={}
diff --git a/start.py b/start.py
deleted file mode 100644
index 8be33e8..0000000
--- a/start.py
+++ /dev/null
@@ -1,211 +0,0 @@
-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-import random
-import time
-import requests
-from dns.qCloud import QcloudApiv3 # QcloudApiv3 DNSPod 的 API 更新了 By github@z0z0r4
-from dns.aliyun import AliApi
-from dns.huawei import HuaWeiApi
-from dns.nameSilo import NameSiloClient
-from log import Logger
-import traceback
-
-
-#CM:移动 CU:联通 CT:电信 AB:境外 DEF:默认
-#修改需要更改的dnspod域名和子域名
-#NameSilo不支持多线解析,只能选DEF默认线路
-DOMAINS = {
- "quanxxxhost.com": {"@": ["CM","CU","CT"]}
-}
-
-#解析生效条数
-#免费的DNSPod相同线路最多支持2条解析
-AFFECT_NUM = 2
-
-#DNS解析服务商 DNSPod-1 阿里云-2 如华为云-3 NameSilo-4
-DNS_SERVER = 4
-
-#如果使用华为云解析 需要从API凭证-项目列表中获取
-REGION_HW = 'cn-east-3'
-
-#如果使用阿里云解析 REGION出现错误再修改 默认不需要修改 https://help.aliyun.com/document_detail/198326.html
-REGION_ALI = 'cn-hongkong'
-
-#解析生效时间,默认为600秒 如果不是DNS付费版用户 不要修改!!!
-#如果是NameSilo解析最小为3600
-TTL = 600
-
-#v4为筛选出IPv4的IP v6为筛选出IPv6的IP
-#目前仅支持v4
-TYPE = 'v4'
-
-#API 密钥
-#腾讯云后台获取 https://console.cloud.tencent.com/cam/capi
-#阿里云后台获取 https://help.aliyun.com/document_detail/53045.html?spm=a2c4g.11186623.2.11.2c6a2fbdh13O53 注意需要添加DNS控制权限 AliyunDNSFullAccess
-#华为云后台获取 https://support.huaweicloud.com/devg-apisign/api-sign-provide-aksk.html
-#NameSilo后台获取 https://www.namesilo.com/account/api-manager NameSilo只用填SECRETKEY即可
-SECRETID = 'LTAI5xxxxxxxxxYWRedp9Y'
-SECRETKEY = '7288bxxxxxxxxx23a332'
-
-log_cf2dns = Logger('cf2dns.log', level='debug')
-
-def get_optimization_ip():
- try:
- headers = headers = {'Content-Type': 'application/json'}
- data = {}
- response = requests.post('https://vps789.com/public/sum/cfIpApi', json=data, headers=headers)
- if response.status_code == 200:
- return response.json()
- else:
- log_cf2dns.logger.error("CHANGE OPTIMIZATION IP ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: REQUEST STATUS CODE IS NOT 200")
- return None
- except Exception as e:
- log_cf2dns.logger.error("CHANGE OPTIMIZATION IP ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(e))
- return None
-
-#s_info已存在的ip,c_info 最新的优选cfip
-def changeDNS(line, s_info, c_info, domain, sub_domain, cloud):
- global AFFECT_NUM, TYPE
- if TYPE == 'v6':
- recordType = "AAAA"
- else:
- recordType = "A"
-
- lines = {"CM": "移动", "CU": "联通", "CT": "电信", "AB": "境外", "DEF": "默认"}
- line = lines[line]
-
- try:
- create_num = AFFECT_NUM - len(s_info)
- # 如果线路能解析的ip已满,就用cfip一个一个去替换原来的ip解析
- if create_num == 0:
- for info in s_info:
- if len(c_info) == 0:
- break
- 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, recordType, 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:
- log_cf2dns.logger.error("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"] )
- # 如果线路还可以解析更多的ip,就添加cfip解析,直到用完
- elif create_num > 0:
- for i in range(create_num):
- if len(c_info) == 0:
- break
- 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, recordType, 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:
- log_cf2dns.logger.error("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"] )
- # 如果线路能解析的ip已超出配额,就用cfip一个一个去替换原来的ip解析
- else:
- for info in s_info:
- if create_num == 0 or len(c_info) == 0:
- break
- 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 = cloud.change_record(domain, info["recordId"], sub_domain, cf_ip, recordType, 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:
- log_cf2dns.logger.error("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:
- log_cf2dns.logger.error("CHANGE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(e))
-
-def main(cloud):
- global AFFECT_NUM, TYPE
- if TYPE == 'v6':
- recordType = "AAAA"
- else:
- recordType = "A"
- if len(DOMAINS) > 0:
- try:
- cfips = get_optimization_ip()
- if cfips == None or cfips["code"] != 0:
- log_cf2dns.logger.error("GET CLOUDFLARE IP ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(cfips["data"]))
- return
- cf_cmips = cfips["data"]["CM"]
- cf_cuips = cfips["data"]["CU"]
- cf_ctips = cfips["data"]["CT"]
- cf_defips = cfips["data"]["AllAvg"]
- for domain, sub_domains in DOMAINS.items():
- for sub_domain, lines in sub_domains.items():
- if DNS_SERVER == 4 and len(lines)!=1:
- log_cf2dns.logger.info("域名解析为NameSilo时,线路只能填DEF")
- return
-
- #下面5个数组存的是不同线路最新获取的优选IP列表
- temp_cf_cmips = cf_cmips.copy()
- temp_cf_cuips = cf_cuips.copy()
- temp_cf_ctips = cf_ctips.copy()
- temp_cf_abips = cf_ctips.copy()
- temp_cf_defips = cf_defips.copy()
- if DNS_SERVER == 1:
- ret = cloud.get_record(domain, 20, sub_domain, "CNAME")
- if ret["code"] == 0:
- for record in ret["data"]["records"]:
- if record["line"] == "移动" or record["line"] == "联通" or record["line"] == "电信":
- retMsg = cloud.del_record(domain, record["id"])
- if(retMsg["code"] == 0):
- log_cf2dns.logger.info("DELETE DNS SUCCESS: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----DOMAIN: " + domain + "----SUBDOMAIN: " + sub_domain + "----RECORDLINE: "+record["line"] )
- else:
- 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, recordType)
- # ret["code"] == 0 就是DNS_SERVER == 1
- 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
- #下面5个数组存的是已存在的DNS解析列表
- cm_info = []
- cu_info = []
- ct_info = []
- ab_info = []
- def_info = []
- for record in ret["data"]["records"]:
- info = {}
- info["recordId"] = record["id"]
- info["value"] = record["value"]
- if record["line"] == "移动":
- cm_info.append(info)
- elif record["line"] == "联通":
- cu_info.append(info)
- elif record["line"] == "电信":
- ct_info.append(info)
- elif record["line"] == "境外":
- ab_info.append(info)
- elif record["line"] == "默认":
- def_info.append(info)
- for line in lines:
- if line == "CM":
- changeDNS("CM", cm_info, temp_cf_cmips, domain, sub_domain, cloud)
- elif line == "CU":
- changeDNS("CU", cu_info, temp_cf_cuips, domain, sub_domain, cloud)
- elif line == "CT":
- changeDNS("CT", ct_info, temp_cf_ctips, domain, sub_domain, cloud)
- elif line == "AB":
- changeDNS("AB", ab_info, temp_cf_abips, domain, sub_domain, cloud)
- elif line == "DEF":
- changeDNS("DEF", def_info, temp_cf_defips, domain, sub_domain, cloud)
- except Exception as e:
- traceback.print_exc()
- log_cf2dns.logger.error("CHANGE DNS ERROR: ----Time: " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "----MESSAGE: " + str(e))
-
-
-if __name__ == '__main__':
- if DNS_SERVER == 1:
- cloud = QcloudApiv3(SECRETID, SECRETKEY)
- elif DNS_SERVER == 2:
- cloud = AliApi(SECRETID, SECRETKEY, REGION_ALI)
- elif DNS_SERVER == 3:
- cloud = HuaWeiApi(SECRETID, SECRETKEY, REGION_HW)
- elif DNS_SERVER == 4:
- cloud = NameSiloClient(SECRETKEY)
- main(cloud)
\ No newline at end of file