Create ddns-dnspod

This commit is contained in:
Stille 2021-06-11 14:26:01 +08:00
parent 1b9d8f5c29
commit 6b8bda2d07
9 changed files with 566 additions and 0 deletions

42
.github/workflows/ddns-dnspod.yml vendored Normal file
View File

@ -0,0 +1,42 @@
name: "ddns-dnspod docker build"
env:
PROJECT: ddns-dnspod
on:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
env:
ACTIONS_ALLOW_UNSECURE_COMMANDS: true
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Set tag
id: tag
run: |
TAG=$(cat ${{ env.PROJECT }}/Dockerfile | awk 'NR==4 {print $3}')
echo "::set-env name=TAG::$TAG"
- name: Docker Hub login
env:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
run: |
echo "${DOCKER_PASSWORD}" | docker login --username ${DOCKER_USERNAME} --password-stdin
- name: Set up Docker Buildx
id: buildx
uses: crazy-max/ghaction-docker-buildx@v1
with:
buildx-version: latest
- name: Build Dockerfile
env:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
run: |
docker buildx build \
--platform=linux/amd64,linux/arm64 \
--output "type=image,push=true" \
--file ${{ env.PROJECT }}/Dockerfile ./${{ env.PROJECT }} \
--tag $(echo "${DOCKER_USERNAME}" | tr '[:upper:]' '[:lower:]')/${{ env.PROJECT }}:latest \
--tag $(echo "${DOCKER_USERNAME}" | tr '[:upper:]' '[:lower:]')/${{ env.PROJECT }}:${TAG}

70
ddns-dnspod/.gitignore vendored Normal file
View File

@ -0,0 +1,70 @@
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
.idea/
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
ddnspod.cfg
# VSCODE
.vscode/settings.json
.vscode/tasks.json
tasks.json

11
ddns-dnspod/Dockerfile Normal file
View File

@ -0,0 +1,11 @@
FROM python:3-alpine
MAINTAINER strahe <u@strahe.com>
ENV VERSION 2021-06-11
WORKDIR /app
ADD . /app
ENTRYPOINT ["python", "ddns.py"]

72
ddns-dnspod/LICENSE Normal file
View File

@ -0,0 +1,72 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

42
ddns-dnspod/README.md Normal file
View File

@ -0,0 +1,42 @@
# ddns-dnspod
GitHub [stilleshan/dockerfiles](https://github.com/stilleshan/dockerfiles)
Docker [stilleshan/ddns-dnspod](https://hub.docker.com/r/stilleshan/ddns-dnspod)
> *docker image support for X86 and ARM*
## 使用
### docker 启动
```shell
docker run -d \
--restart=always \
--name=dnspod-ddns \
-e "login_token=token_id,token" \
-e "domain=domain.com" \
-e "sub_domain=www" \
-e "interval=10" \
-e "ip_count=1" \
stilleshan/ddns-dnspod
```
- login_token: 填写`dnspod.cn`上申请的`API TOKEN`
- domain: 填写`根域名`
- sub_domain: 填写`子域名`
### 示例
> 使用二级域名来作为 ddns 域名,例如以下示例使用 ddns.ioiox.com ,需要使用的正式域名添加 CNAME 指向 ddns.ioiox.com 即可.
```shell
docker run -d \
--restart=always \
--name=dnspod-ddns \
-e "login_token=123456,5MTlmZRFZrWkdFMVTU2VFE9PX" \
-e "domain=ioiox.com" \
-e "sub_domain=ddns" \
-e "interval=10" \
-e "ip_count=1" \
stilleshan/ddns-dnspod
```
## 参考
[群晖NAS网络服务 - docker 部署配置腾讯云 DNSPod DDNS 动态域名解析](https://www.ioiox.com/archives/112.html)
更多请参考原始仓库 [strahe/dnspod-ddns](https://github.com/strahe/dnspod-ddns)

142
ddns-dnspod/config.py Normal file
View File

@ -0,0 +1,142 @@
import os
import getopt
import sys
import logging
# 定义配置文件目录
# linux
config_path = '/etc/dnspod/ddnsrc'
# windows
if os.name == 'nt':
config_path = 'ddnspod.cfg'
# 配置属性,及其默认参数
cfg = {}
# dnspod 登录配置
cfg["login_token"] = '' # 默认空参数,要求用户必填 格式 'token_id,token' # 登录token
# ddns 基本配置
cfg["sub_domain"] = '' # 默认空参数,要求用户必填 #格式 'www' # 子域名
cfg["domain"] = '' # 默认空参数,要求用户必填 #格式 'domain.com' # 域名
cfg["interval"] = '5' # 最小更新间隔
cfg["record_id"] = '{auto}' # 记录id程序自动生成
cfg["current_ip"] = '{auto}' # 当前ip程序自动生成
cfg["email"] = '' # 默认空参数,要求用户必填 #格式 'you@email.com'
# ip 池
cfg["ip_count"] = '1' # 此域名拥有的ip数量默认为 1 OpenWrt 玩家可能会有多个IP
cfg["ip_pool"] = '{auto}' # ip 池 ..,程序自动生成
cfg["last_update_time"] = '{auto}' # 上次更新成功时间戳,程序自动生成
def read_config():
# 后面读出的数据会覆盖前面的
read_config_from_file()
read_config_from_env()
read_config_from_argv()
def print_help():
max_key_len = max([len(key) for key in cfg.keys()])
print("ddns.py [-h|...]")
print("命令行方式调用,可用的参数如下:")
for name in cfg.keys():
print(' --%-' + str(max_key_len) + 's <value>' % name)
print("配置优先级: 命令行 > 环境变量 > 配置文件")
print("当前配置文件目录为:%s" % config_path)
def read_config_from_file():
try:
with open(config_path, 'rU') as fp:
for line in fp:
pair = [x.strip() for x in line.split('=')]
if pair[0] and pair[1]:
cfg[pair[0].lower()] = pair[1]
except:
pass
def read_config_from_env():
for key in cfg:
if os.getenv(key) is not None:
cfg[key] = os.getenv(key)
# 从命令行读取参数
def read_config_from_argv():
available_args = [x + "=" for x in cfg.keys()]
try:
opts, _ = getopt.getopt(sys.argv[1:], "h", available_args)
for opt, arg in opts:
if opt == '-h':
print_help()
sys.exit()
if opt.startswith('--'):
pair = [opt[2:], arg]
if pair[0] and pair[1]:
cfg[pair[0].lower()] = pair[1]
except getopt.GetoptError:
print_help()
sys.exit(1)
def save_config():
try:
save_config_to_env()
save_config_to_file()
except NotImplementedError as err:
logging.error("FAILED to save config:" + str(err))
# 不太清楚这个函数能干啥用 = = 写着玩。。。
def save_config_to_env():
for key in cfg:
os.environ[key] = cfg[key]
# 保存配置到文件… 这个函数现在会把配置文件里的注释也删掉……
def save_config_to_file():
max_key_len = max([len(key) for key in cfg.keys()])
try:
with open(config_path, "w+") as f:
f.writelines([
('%-'+str(max_key_len)+'s=%s\n') % (key, cfg[key])
for key in cfg.keys()
])
except IOError as err:
logging.error("FAILED to save config to file: " + str(err))
# 检查配置是否齐全
def check_config():
if not (
cfg['login_token'] and
cfg['domain'] and
cfg['sub_domain']):
logging.fatal('config error: need login info')
exit()
try:
if not(int(cfg["interval"])):
logging.fatal('interval error')
exit()
if not(int(cfg["ip_count"])):
logging.fatal('ip_count error')
exit()
except:
logging.fatal('config error')
exit()
logging.info('config checked')
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO,
format='%(levelname)-8s: %(message)s')
# 测试配置文件
logging.info("init cfg: %s" % cfg)
read_config()
logging.info("read cfg: %s" % cfg)
check_config()

112
ddns-dnspod/ddns.py Normal file
View File

@ -0,0 +1,112 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
import os
import json
import signal
import functools
import logging
import socket
import time
from urllib import request, error, parse
from config import read_config, save_config, check_config, cfg
from get_ip import get_ip
def header():
h = {
'User-Agent': 'Client/0.0.1 ({})'.format(cfg['email'])
}
return h
def get_record_id(domain, sub_domain):
url = 'https://dnsapi.cn/Record.List'
params = parse.urlencode({
'login_token': cfg['login_token'],
'format': 'json',
'domain': domain
})
req = request.Request(url=url, data=params.encode('utf-8'), method='POST', headers=header())
try:
resp = request.urlopen(req).read().decode()
except (error.HTTPError, error.URLError, socket.timeout):
return None
records = json.loads(resp).get('records', {})
for item in records:
if item.get('name') == sub_domain:
return item.get('id')
return None
def update_record():
url = 'https://dnsapi.cn/Record.Ddns'
params = parse.urlencode({
'login_token': cfg['login_token'],
'format': 'json',
'domain': cfg['domain'],
'sub_domain': cfg['sub_domain'],
'record_id': cfg['record_id'],
'record_line': '默认'
})
req = request.Request(url=url, data=params.encode('utf-8'), method='POST', headers=header())
resp = request.urlopen(req).read().decode()
records = json.loads(resp)
cfg['last_update_time'] = str(time.gmtime())
logging.info("record updated: %s" % records)
# async def main():
def main():
while 1:
current_ip = get_ip()
if current_ip:
# 对于拥有多个出口 IP 负载均衡的服务器,上面的 get_ip() 函数会在几个 ip 之间不停切换
# 然后频繁进入这个判断,进行 update_record(),然后很快就会触发 API Limited 了
# 于是建立一个IP池记载这个服务器的几个出口IP以免频繁切换
ip_count = int(cfg['ip_count'])
ip_pool = cfg['ip_pool'].split(',')[:ip_count]
cfg['current_ip'] = current_ip
if current_ip not in ip_pool:
# new ip found
logging.info("new ip found: %s", current_ip)
ip_pool.insert(0, current_ip)
cfg['ip_pool'] = ','.join([str(x) for x in ip_pool[:ip_count]])
update_record()
save_config()
else:
logging.error('get current ip FAILED.')
try:
interval = int(cfg['interval'])
except ValueError:
interval = 5
# await asyncio.sleep(interval)
time.sleep(interval)
def ask_exit(_sig_name):
logging.warning('got signal {}: exit'.format(_sig_name))
loop.stop()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s : %(message)s')
logging.info('start...')
read_config()
check_config()
cfg['record_id'] = get_record_id(cfg['domain'], cfg['sub_domain'])
logging.info("get record_id: %s" % str(cfg['record_id']))
logging.info("watching ip for ddns: %s.%s" % (cfg['sub_domain'], cfg['domain']))
loop = asyncio.get_event_loop()
for sig_name in ('SIGINT', 'SIGTERM'):
try:
loop.add_signal_handler(getattr(signal, sig_name), functools.partial(ask_exit, sig_name))
except NotImplementedError:
pass # 使兼容 WINDOWS
try:
loop.run_until_complete(main())
except (KeyboardInterrupt, RuntimeError):
logging.info('stop...')
finally:
loop.close()

View File

@ -0,0 +1,6 @@
LOGIN_TOKEN=token_id,token
DOMAIN=domain.com
SUB_DOMAIN=www
INTERVAL=5
EMAIL=you@email.com
IP_COUNT=1

69
ddns-dnspod/get_ip.py Normal file
View File

@ -0,0 +1,69 @@
import re
import logging
import socket
from urllib import request, error, parse
# 匹配合法 IP 地址
regex_ip = re.compile(
r"\D*("
+ r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\."
+ r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
+ r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
+ r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)"
+ r")\D*")
# 增强鲁棒性,用多种方式获取 IP
def get_ip():
return (get_ip_by_ipip()
or get_ip_by_httpbin()
or get_ip_by_httpbin_direct_1()
or get_ip_by_httpbin_direct_2() )
# 这几个函数会在 DNS 遭受污染时失效
def get_ip_by_ipip():
url = 'http://myip.ipip.net/'
try:
resp = request.urlopen(url=url, timeout=10).read()
return regex_ip.match(resp.decode("utf-8")).group(1)
except Exception as e:
logging.warning("get_ip_by_ipip FAILED, error: %s", str(e))
return None
def get_ip_by_httpbin():
url = 'http://www.httpbin.org/ip'
try:
resp = request.urlopen(url=url, timeout=10).read()
return regex_ip.match(resp.decode("utf-8")).group(1)
except Exception as e:
logging.warning("get_ip_by_httpbin FAILED, error: %s", str(e))
return None
# 这个函数可以在本地 DNS 遭受污染的时候获取到IP
# 如需模拟DNS污染可以在HOSTS文件里加入 127.0.0.1 www.httpbin.org
def get_ip_by_httpbin_direct_1():
url = 'http://52.5.182.176/ip'
try:
req = request.Request(url=url, method='GET', headers={'Host': 'www.httpbin.org'})
resp = request.urlopen(req).read()
return regex_ip.match(resp.decode("utf-8")).group(1)
except Exception as e:
logging.warning("get_ip_by_httpbin_direct_1 FAILED, error: %s", str(e))
return None
def get_ip_by_httpbin_direct_2():
url = 'http://52.44.230.61/ip'
try:
req = request.Request(url=url, method='GET', headers={'Host': 'www.httpbin.org'})
resp = request.urlopen(req).read()
return regex_ip.match(resp.decode("utf-8")).group(1)
except Exception as e:
logging.warning("get_ip_by_httpbin_direct_2 FAILED, error: %s", str(e))
return None
# 测试
if __name__ == '__main__':
print(get_ip() )
print(get_ip_by_ipip() )
print(get_ip_by_httpbin() )
print(get_ip_by_httpbin_direct_1() )