ddns 4.0.1__py2.py3-none-any.whl → 4.1.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ddns might be problematic. Click here for more details.

ddns/util/config.py DELETED
@@ -1,317 +0,0 @@
1
- # -*- coding:utf-8 -*-
2
- from argparse import Action, ArgumentParser, Namespace, RawTextHelpFormatter
3
- from json import load as loadjson, dump as dumpjson
4
- from os import stat, environ, path
5
- from logging import critical, error, getLevelName
6
- from ast import literal_eval
7
-
8
- import platform
9
- import sys
10
-
11
-
12
- __cli_args = Namespace()
13
- __config = {} # type: dict
14
- log_levels = [
15
- "CRITICAL", # 50
16
- "ERROR", # 40
17
- "WARNING", # 30
18
- "INFO", # 20
19
- "DEBUG", # 10
20
- "NOTSET", # 0
21
- ]
22
-
23
- # 支持数组的参数列表
24
- ARRAY_PARAMS = ["index4", "index6", "ipv4", "ipv6", "proxy"]
25
- # 简单数组,支持’,’, ‘;’ 分隔的参数列表
26
- SIMPLE_ARRAY_PARAMS = ["ipv4", "ipv6", "proxy"]
27
-
28
-
29
- def str2bool(v):
30
- """
31
- parse string to boolean
32
- """
33
- if isinstance(v, bool):
34
- return v
35
- if v.lower() in ("yes", "true", "t", "y", "1"):
36
- return True
37
- elif v.lower() in ("no", "false", "f", "n", "0"):
38
- return False
39
- else:
40
- return v
41
-
42
-
43
- def log_level(value):
44
- """
45
- parse string to log level
46
- or getattr(logging, value.upper())
47
- """
48
- return getLevelName(value.upper())
49
-
50
-
51
- def parse_array_string(value, enable_simple_split):
52
- """
53
- 解析数组字符串
54
- 仅当 trim 之后以 '[' 开头以 ']' 结尾时,才尝试使用 ast.literal_eval 解析
55
- 默认返回原始字符串
56
- """
57
- if not isinstance(value, str):
58
- return value
59
-
60
- trimmed = value.strip()
61
- if trimmed.startswith("[") and trimmed.endswith("]"):
62
- try:
63
- # 尝试使用 ast.literal_eval 解析数组
64
- parsed_value = literal_eval(trimmed)
65
- # 确保解析结果是列表或元组
66
- if isinstance(parsed_value, (list, tuple)):
67
- return list(parsed_value)
68
- except (ValueError, SyntaxError) as e:
69
- # 解析失败时返回原始字符串
70
- error("Failed to parse array string: %s. Exception: %s", value, e)
71
- elif enable_simple_split:
72
- # 尝试使用逗号或分号分隔符解析
73
- sep = None
74
- if ',' in trimmed:
75
- sep = ','
76
- elif ';' in trimmed:
77
- sep = ';'
78
- if sep:
79
- return [item.strip() for item in trimmed.split(sep) if item.strip()]
80
- return value
81
-
82
-
83
- def get_system_info_str():
84
- system = platform.system()
85
- release = platform.release()
86
- machine = platform.machine()
87
- arch = platform.architecture()[0] # '64bit' or '32bit'
88
-
89
- return "{}-{} {} ({})".format(system, release, machine, arch)
90
-
91
-
92
- def get_python_info_str():
93
- version = platform.python_version()
94
- branch, py_build_date = platform.python_build()
95
- return "Python-{} {} ({})".format(version, branch, py_build_date)
96
-
97
-
98
- def init_config(description, doc, version, date):
99
- """
100
- 配置
101
- """
102
- global __cli_args
103
- parser = ArgumentParser(
104
- description=description, epilog=doc, formatter_class=RawTextHelpFormatter
105
- )
106
- sysinfo = get_system_info_str()
107
- pyinfo = get_python_info_str()
108
- version_str = "v{} ({})\n{}\n{}".format(version, date, pyinfo, sysinfo)
109
- parser.add_argument("-v", "--version", action="version", version=version_str)
110
- parser.add_argument(
111
- "-c", "--config", metavar="FILE", help="load config file [配置文件路径]"
112
- )
113
- parser.add_argument(
114
- "--debug",
115
- action="store_true",
116
- help="debug mode [调试模式等效 --log.level=DEBUG]",
117
- )
118
-
119
- # 参数定义
120
- parser.add_argument(
121
- "--dns",
122
- help="DNS provider [DNS服务提供商]",
123
- choices=[
124
- "alidns",
125
- "cloudflare",
126
- "dnscom",
127
- "dnspod",
128
- "dnspod_com",
129
- "he",
130
- "huaweidns",
131
- "callback",
132
- ],
133
- )
134
- parser.add_argument("--id", help="API ID or email [对应账号ID或邮箱]")
135
- parser.add_argument("--token", help="API token or key [授权凭证或密钥]")
136
- parser.add_argument(
137
- "--index4",
138
- nargs="*",
139
- action=ExtendAction,
140
- metavar="RULE",
141
- help="IPv4 rules [获取IPv4方式, 多次可配置多规则]",
142
- )
143
- parser.add_argument(
144
- "--index6",
145
- nargs="*",
146
- action=ExtendAction,
147
- metavar="RULE",
148
- help="IPv6 rules [获取IPv6方式, 多次可配置多规则]",
149
- )
150
- parser.add_argument(
151
- "--ipv4",
152
- nargs="*",
153
- action=ExtendAction,
154
- metavar="DOMAIN",
155
- help="IPv4 domains [IPv4域名列表, 可配置多个域名]",
156
- )
157
- parser.add_argument(
158
- "--ipv6",
159
- nargs="*",
160
- action=ExtendAction,
161
- metavar="DOMAIN",
162
- help="IPv6 domains [IPv6域名列表, 可配置多个域名]",
163
- )
164
- parser.add_argument("--ttl", type=int, help="DNS TTL(s) [设置域名解析过期时间]")
165
- parser.add_argument(
166
- "--proxy",
167
- nargs="*",
168
- action=ExtendAction,
169
- help="HTTP proxy [设置http代理,可配多个代理连接]",
170
- )
171
- parser.add_argument(
172
- "--cache",
173
- type=str2bool,
174
- nargs="?",
175
- const=True,
176
- help="set cache [启用缓存开关,或传入保存路径]",
177
- )
178
- parser.add_argument(
179
- "--no-cache",
180
- dest="cache",
181
- action="store_const",
182
- const=False,
183
- help="disable cache [关闭缓存等效 --cache=false]",
184
- )
185
- parser.add_argument(
186
- "--log.file", metavar="FILE", help="log file [日志文件,默认标准输出]"
187
- )
188
- parser.add_argument("--log.level", type=log_level, metavar="|".join(log_levels))
189
- parser.add_argument(
190
- "--log.format", metavar="FORMAT", help="log format [设置日志打印格式]"
191
- )
192
- parser.add_argument(
193
- "--log.datefmt", metavar="FORMAT", help="date format [日志时间打印格式]"
194
- )
195
-
196
- __cli_args = parser.parse_args()
197
- if __cli_args.debug:
198
- # 如果启用调试模式,则设置日志级别为 DEBUG
199
- setattr(__cli_args, "log.level", log_level("DEBUG"))
200
-
201
- is_configfile_required = not get_config("token") and not get_config("id")
202
- config_file = get_config("config")
203
- if not config_file:
204
- # 未指定配置文件且需要读取文件时,依次查找
205
- cfgs = [
206
- path.abspath("config.json"),
207
- path.expanduser("~/.ddns/config.json"),
208
- "/etc/ddns/config.json",
209
- ]
210
- config_file = next((cfg for cfg in cfgs if path.isfile(cfg)), cfgs[0])
211
-
212
- if path.isfile(config_file):
213
- __load_config(config_file)
214
- __cli_args.config = config_file
215
- elif is_configfile_required:
216
- error("Config file is required, but not found: %s", config_file)
217
- # 如果需要配置文件但没有指定,则自动生成
218
- if generate_config(config_file):
219
- sys.stdout.write("Default configure file %s is generated.\n" % config_file)
220
- sys.exit(1)
221
- else:
222
- sys.exit("fail to load config from file: %s\n" % config_file)
223
-
224
-
225
- def __load_config(config_path):
226
- """
227
- 加载配置
228
- """
229
- global __config
230
- try:
231
- with open(config_path, "r") as configfile:
232
- __config = loadjson(configfile)
233
- __config["config_modified_time"] = stat(config_path).st_mtime
234
- if "log" in __config:
235
- if "level" in __config["log"] and __config["log"]["level"] is not None:
236
- __config["log.level"] = log_level(__config["log"]["level"])
237
- if "file" in __config["log"]:
238
- __config["log.file"] = __config["log"]["file"]
239
- if "format" in __config["log"]:
240
- __config["log.format"] = __config["log"]["format"]
241
- if "datefmt" in __config["log"]:
242
- __config["log.datefmt"] = __config["log"]["datefmt"]
243
- elif "log.level" in __config:
244
- __config["log.level"] = log_level(__config["log.level"])
245
- except Exception as e:
246
- critical("Failed to load config file `%s`: %s", config_path, e)
247
- raise
248
- # 重新抛出异常
249
-
250
-
251
- def get_config(key, default=None):
252
- """
253
- 读取配置
254
- 1. 命令行参数
255
- 2. 配置文件
256
- 3. 环境变量
257
- """
258
- if hasattr(__cli_args, key) and getattr(__cli_args, key) is not None:
259
- return getattr(__cli_args, key)
260
- if key in __config:
261
- return __config.get(key)
262
- # 检查环境变量
263
- env_name = "DDNS_" + key.replace(".", "_") # type:str
264
- variations = [env_name, env_name.upper(), env_name.lower()]
265
- value = next((environ.get(v) for v in variations if v in environ), None)
266
-
267
- # 如果找到环境变量值且参数支持数组,尝试解析为数组
268
- if value is not None and key in ARRAY_PARAMS:
269
- return parse_array_string(value, key in SIMPLE_ARRAY_PARAMS)
270
-
271
- return value if value is not None else default
272
-
273
-
274
- class ExtendAction(Action):
275
- """
276
- 兼容 Python <3.8 的 extend action
277
- """
278
-
279
- def __call__(self, parser, namespace, values, option_string=None):
280
- items = getattr(namespace, self.dest, None)
281
- if items is None:
282
- items = []
283
- # values 可能是单个值或列表
284
- if isinstance(values, list):
285
- items.extend(values)
286
- else:
287
- items.append(values)
288
- setattr(namespace, self.dest, items)
289
-
290
-
291
- def generate_config(config_path):
292
- """
293
- 生成配置文件
294
- """
295
- configure = {
296
- "$schema": "https://ddns.newfuture.cc/schema/v4.0.json",
297
- "id": "YOUR ID or EMAIL for DNS Provider",
298
- "token": "YOUR TOKEN or KEY for DNS Provider",
299
- "dns": "dnspod",
300
- "ipv4": ["newfuture.cc", "ddns.newfuture.cc"],
301
- "ipv6": ["newfuture.cc", "ipv6.ddns.newfuture.cc"],
302
- "index4": "default",
303
- "index6": "default",
304
- "ttl": None,
305
- "proxy": None,
306
- "log": {"level": "INFO"},
307
- }
308
- try:
309
- with open(config_path, "w") as f:
310
- dumpjson(configure, f, indent=2, sort_keys=True)
311
- return True
312
- except IOError:
313
- critical("Cannot open config file to write: `%s`!", config_path)
314
- return False
315
- except Exception as e:
316
- critical("Failed to write config file `%s`: %s", config_path, e)
317
- return False
ddns/util/ip.py DELETED
@@ -1,96 +0,0 @@
1
- #!/usr/bin/env python
2
- # -*- coding:utf-8 -*-
3
- from re import compile
4
- from os import name as os_name, popen
5
- from socket import socket, getaddrinfo, gethostname, AF_INET, AF_INET6, SOCK_DGRAM
6
- from logging import debug, error
7
- try: # python3
8
- from urllib.request import urlopen, Request
9
- except ImportError: # python2
10
- from urllib2 import urlopen, Request
11
-
12
- # IPV4正则
13
- IPV4_REG = r'((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])'
14
- # IPV6正则
15
- # https://community.helpsystems.com/forums/intermapper/miscellaneous-topics/5acc4fcf-fa83-e511-80cf-0050568460e4
16
- IPV6_REG = r'((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))' # noqa: E501
17
-
18
-
19
- def default_v4(): # 默认连接外网的ipv4
20
- s = socket(AF_INET, SOCK_DGRAM)
21
- s.connect(("1.1.1.1", 53))
22
- ip = s.getsockname()[0]
23
- s.close()
24
- return ip
25
-
26
-
27
- def default_v6(): # 默认连接外网的ipv6
28
- s = socket(AF_INET6, SOCK_DGRAM)
29
- s.connect(('1:1:1:1:1:1:1:1', 8))
30
- ip = s.getsockname()[0]
31
- s.close()
32
- return ip
33
-
34
-
35
- def local_v6(i=0): # 本地ipv6地址
36
- info = getaddrinfo(gethostname(), 0, AF_INET6)
37
- debug(info)
38
- return info[int(i)][4][0]
39
-
40
-
41
- def local_v4(i=0): # 本地ipv4地址
42
- info = getaddrinfo(gethostname(), 0, AF_INET)
43
- debug(info)
44
- return info[int(i)][-1][0]
45
-
46
-
47
- def _open(url, reg):
48
- try:
49
- debug("open: %s", url)
50
- res = urlopen(
51
- Request(url, headers={'User-Agent': 'Mozilla/5.0 ddns'}), timeout=60
52
- ).read().decode('utf8', 'ignore')
53
- debug("response: %s", res)
54
- return compile(reg).search(res).group()
55
- except Exception as e:
56
- error(e)
57
-
58
-
59
- def public_v4(url="https://api-ipv4.ip.sb/ip", reg=IPV4_REG): # 公网IPV4地址
60
- return _open(url, reg)
61
-
62
-
63
- def public_v6(url="https://api-ipv6.ip.sb/ip", reg=IPV6_REG): # 公网IPV6地址
64
- return _open(url, reg)
65
-
66
-
67
- def _ip_regex_match(parrent_regex, match_regex):
68
-
69
- ip_pattern = compile(parrent_regex)
70
- matcher = compile(match_regex)
71
-
72
- if os_name == 'nt': # windows:
73
- cmd = 'ipconfig'
74
- else:
75
- cmd = 'ip address || ifconfig 2>/dev/null'
76
-
77
- for s in popen(cmd).readlines():
78
- addr = ip_pattern.search(s)
79
- if addr and matcher.match(addr.group(1)):
80
- return addr.group(1)
81
-
82
-
83
- def regex_v4(reg): # ipv4 正则提取
84
- if os_name == 'nt': # Windows: IPv4 xxx: 192.168.1.2
85
- regex_str = r'IPv4 .*: ((?:\d{1,3}\.){3}\d{1,3})\W'
86
- else:
87
- regex_str = r'inet (?:addr\:)?((?:\d{1,3}\.){3}\d{1,3})[\s/]'
88
- return _ip_regex_match(regex_str, reg)
89
-
90
-
91
- def regex_v6(reg): # ipv6 正则提取
92
- if os_name == 'nt': # Windows: IPv4 xxx: ::1
93
- regex_str = r'IPv6 .*: ([\:\dabcdef]*)?\W'
94
- else:
95
- regex_str = r'inet6 (?:addr\:\s*)?([\:\dabcdef]*)?[\s/%]'
96
- return _ip_regex_match(regex_str, reg)