Skip to content

Commit

Permalink
Merge pull request #105 from NewFuture/fix-dnspod_com-104
Browse files Browse the repository at this point in the history
fix(config): fix #104 dnspod.com
  • Loading branch information
NewFuture authored Nov 2, 2019
2 parents 373a5a8 + e360ed6 commit 007a41a
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 53 deletions.
23 changes: 13 additions & 10 deletions dns/alidns.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,12 @@
__author__ = 'New Future'
# __all__ = ["request", "ID", "TOKEN", "PROXY"]

ID = "id"
TOKEN = "TOKEN"
PROXY = None # 代理设置

class Config:
ID = "id"
TOKEN = "TOKEN"
PROXY = None # 代理设置
TTL = 600


class API:
Expand All @@ -44,7 +47,7 @@ def signature(params):
params.update({
'Format': 'json',
'Version': '2015-01-09',
'AccessKeyId': ID,
'AccessKeyId': Config.ID,
'Timestamp': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': uuid4(),
Expand All @@ -55,7 +58,7 @@ def signature(params):
sign = API.METHOD + "&" + quote_plus("/") + "&" + quote(query, safe='')
debug("signString: %s", sign)

sign = hmac((TOKEN + "&").encode('utf-8'),
sign = hmac((Config.TOKEN + "&").encode('utf-8'),
sign.encode('utf-8'), sha1).digest()
sign = b64encode(sign).strip()
params["Signature"] = sign
Expand All @@ -71,22 +74,22 @@ def request(param=None, **params):
params = signature(params)
info("%s: %s", API.SITE, params)

if PROXY:
conn = HTTPSConnection(PROXY)
if Config.PROXY:
conn = HTTPSConnection(Config.PROXY)
conn.set_tunnel(API.SITE, 443)
else:
conn = HTTPSConnection(API.SITE)
conn.request(API.METHOD, '/', urlencode(params),
{"Content-type": "application/x-www-form-urlencoded"})
response = conn.getresponse()
data = response.read()
data = response.read().decode('utf8')
conn.close()

if response.status < 200 or response.status >= 300:
warning('%s : error:%s', params['Action'], data)
warning('%s : error[%d]: %s', params['Action'], response.status, data)
raise Exception(data)
else:
data = jsondecode(data.decode('utf8'))
data = jsondecode(data)
debug('%s : result:%s', params['Action'], data)
return data

Expand Down
24 changes: 14 additions & 10 deletions dns/cloudflare.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"""

from json import loads as jsondecode, dumps as jsonencode
from logging import debug, info
from logging import debug, info, warning

try:
# python 2
Expand All @@ -20,9 +20,12 @@

__author__ = 'TongYifan'

ID = "AUTH EMAIL" # CloudFlare 验证的是用户Email,等同于其他平台的userID
TOKEN = "API KEY"
PROXY = None # 代理设置

class Config:
ID = "AUTH EMAIL" # CloudFlare 验证的是用户Email,等同于其他平台的userID
TOKEN = "API KEY"
PROXY = None # 代理设置
TTL = 600


class API:
Expand All @@ -38,8 +41,8 @@ def request(method, action, param=None, **params):
params.update(param)

info("%s/%s : %s", API.SITE, action, params)
if PROXY:
conn = HTTPSConnection(PROXY)
if Config.PROXY:
conn = HTTPSConnection(Config.PROXY)
conn.set_tunnel(API.SITE, 443)
else:
conn = HTTPSConnection(API.SITE)
Expand All @@ -54,15 +57,16 @@ def request(method, action, param=None, **params):
params = None
conn.request(method, '/client/v4/zones' + action, params,
{"Content-type": "application/json",
"X-Auth-Email": ID,
"X-Auth-Key": TOKEN})
"X-Auth-Email": Config.ID,
"X-Auth-Key": Config.TOKEN})
response = conn.getresponse()
res = response.read()
res = response.read().decode('utf8')
conn.close()
if response.status < 200 or response.status >= 300:
warning('%s : error[%d]:%s', action, response.status, res)
raise Exception(res)
else:
data = jsondecode(res.decode('utf8'))
data = jsondecode(res)
debug('%s : result:%s', action, data)
if not data:
raise Exception("Empty Response")
Expand Down
24 changes: 14 additions & 10 deletions dns/dnscom.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from hashlib import md5
from json import loads as jsondecode
from logging import debug, info
from logging import debug, info, warning
from time import mktime
from datetime import datetime

Expand All @@ -26,9 +26,12 @@
__author__ = 'Bigjin'
# __all__ = ["request", "ID", "TOKEN", "PROXY"]

ID = "id"
TOKEN = "TOKEN"
PROXY = None # 代理设置

class Config:
ID = "id"
TOKEN = "TOKEN"
PROXY = None # 代理设置
TTL = 600


class API:
Expand All @@ -42,15 +45,15 @@ def signature(params):
计算签名,返回签名后的查询参数
"""
params.update({
'apiKey': ID,
'apiKey': Config.ID,
'timestamp': mktime(datetime.now().timetuple()),
})
query = urlencode(sorted(params.items()))
debug(query)
sign = query
debug("signString: %s", sign)

sign = md5((sign + TOKEN).encode('utf-8')).hexdigest()
sign = md5((sign + Config.TOKEN).encode('utf-8')).hexdigest()
params["hash"] = sign

return params
Expand All @@ -65,22 +68,23 @@ def request(action, param=None, **params):
params = signature(params)
info("%s/api/%s/ : params:%s", API.SITE, action, params)

if PROXY:
conn = HTTPSConnection(PROXY)
if Config.PROXY:
conn = HTTPSConnection(Config.PROXY)
conn.set_tunnel(API.SITE, 443)
else:
conn = HTTPSConnection(API.SITE)

conn.request(API.METHOD, '/api/' + action + '/', urlencode(params),
{"Content-type": "application/x-www-form-urlencoded"})
response = conn.getresponse()
result = response.read()
result = response.read().decode('utf8')
conn.close()

if response.status < 200 or response.status >= 300:
warning('%s : error[%d]:%s', action, response.status, result)
raise Exception(result)
else:
data = jsondecode(result.decode('utf8'))
data = jsondecode(result)
debug('%s : result:%s', action, data)
if data.get('code') != 0:
raise Exception("api error:", data.get('message'))
Expand Down
31 changes: 17 additions & 14 deletions dns/dnspod.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from json import loads as jsondecode
from logging import debug, info, warning
from os import environ
try:
# python 2
from httplib import HTTPSConnection
Expand All @@ -20,10 +21,11 @@
__author__ = 'New Future'


ID = "token id"
TOKEN = "token key"
PROXY = None # 代理设置
TTL = 600
class Config:
ID = "token id"
TOKEN = "token key"
PROXY = None # 代理设置
TTL = 600


class API:
Expand All @@ -43,25 +45,26 @@ def request(action, param=None, **params):

params.update({API.TOKEN_PARAM: '***', 'format': 'json'})
info("%s/%s : %s", API.SITE, action, params)
params[API.TOKEN_PARAM] = "%s,%s" % (ID, TOKEN)

if PROXY:
conn = HTTPSConnection(PROXY)
params[API.TOKEN_PARAM] = "%s,%s" % (Config.ID, Config.TOKEN)
if Config.PROXY:
conn = HTTPSConnection(Config.PROXY)
conn.set_tunnel(API.SITE, 443)
else:
conn = HTTPSConnection(API.SITE)

conn.request(API.METHOD, '/' + action, urlencode(params),
{"Content-type": "application/x-www-form-urlencoded"})
conn.request(API.METHOD, '/' + action, urlencode(params), {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DDNS/%s ([email protected])" % environ.get("DDNS_VERSION", "1.0.0")
})
response = conn.getresponse()
res = response.read()
res = response.read().decode('utf8')
conn.close()

if response.status < 200 or response.status >= 300:
warning('%s : error:%s', action, res)
warning('%s : error[%d]:%s', action, response.status, res)
raise Exception(res)
else:
data = jsondecode(res.decode('utf8'))
data = jsondecode(res)
debug('%s : result:%s', action, data)
if not data:
raise Exception("empty response")
Expand Down Expand Up @@ -169,7 +172,7 @@ def update_record(domain, value, record_type="A"):
else: # create
# http://www.dnspod.cn/docs/records.html#record-create
res = request("Record.Create", domain_id=domainid, value=value,
sub_domain=sub, record_type=record_type, record_line=API.DEFAULT, ttl=TTL)
sub_domain=sub, record_type=record_type, record_line=API.DEFAULT, ttl=Config.TTL)
if res:
did = res.get("record")["id"]
get_records.records[domainid][did] = res.get("record")
Expand Down
24 changes: 15 additions & 9 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
Copyright (c) New Future (MIT License)
""" % (__version__)

environ["DDNS_VERSION"] = "${BUILD_SOURCEBRANCHNAME}"

if getattr(sys, 'frozen', False):
# https://github.com/pyinstaller/pyinstaller/wiki/Recipe-OpenSSL-Certificate
environ['SSL_CERT_FILE'] = path.join(
Expand Down Expand Up @@ -85,11 +87,12 @@ def get_ip(ip_type):
return False
elif str(index).isdigit(): # 数字 local eth
value = getattr(ip, "local_v" + ip_type)(index)
elif index.startswith('cmd:'): # cmd
elif index.startswith('cmd:'): # cmd
value = str(check_output(index[4:]).strip().decode('utf-8'))
elif index.startswith('shell:'): # shell
value = str(check_output(index[6:], shell=True).strip().decode('utf-8'))
elif index.startswith('url:'): # 自定义 url
elif index.startswith('shell:'): # shell
value = str(check_output(
index[6:], shell=True).strip().decode('utf-8'))
elif index.startswith('url:'): # 自定义 url
value = getattr(ip, "public_v" + ip_type)(index[4:])
elif index.startswith('regex:'): # 正则 regex
value = getattr(ip, "regex_v" + ip_type)(index[6:])
Expand Down Expand Up @@ -151,27 +154,30 @@ def main():
action='version', version=__version__)
parser.add_argument('-c', '--config',
default="config.json", help="run with config file [配置文件路径]")
get_config(path=parser.parse_args().config)
config_file = parser.parse_args().config
get_config(path=config_file)
# Dynamicly import the dns module as configuration
dns_provider = str(get_config('dns', 'dnspod').lower())
dns = getattr(__import__('dns', fromlist=[dns_provider]), dns_provider)
dns.ID, dns.TOKEN = get_config('id'), get_config('token')
dns.Config.ID, dns.Config.TOKEN = get_config('id'), get_config('token')
if get_config('debug'):
ip.DEBUG = get_config('debug')
basicConfig(
level=DEBUG,
format='%(asctime)s <%(module)s.%(funcName)s> %(lineno)d@%(pathname)s \n[%(levelname)s] %(message)s')
info("DDNS[%s] run: %s,%s", __version__, os_name, sys.platform)
print("DDNS[", __version__, "] run:", os_name, sys.platform)
print("Configuration was loaded from <==", path.abspath(config_file))
print("=" * 25, ctime(), "=" * 25, sep=' ')

proxy = get_config('proxy') or 'DIRECT'
proxy_list = proxy.strip('; ') .split(';')

cache = get_config('cache', True) and Cache(CACHE_FILE)
if cache is False:
warning("Cache is disabled!")
info("Cache is disabled!")
elif len(cache) < 1 or get_config.time >= cache.time:
warning("Cache file is out of dated.")
cache.clear()
print("=" * 25, ctime(), "=" * 25, sep=' ')
update_ip('4', cache, dns, proxy_list)
update_ip('6', cache, dns, proxy_list)

Expand Down

0 comments on commit 007a41a

Please sign in to comment.