本帖最后由 话痨司机啊 于 2022-5-25 20:20 编辑
之前我自己电脑上的DDNS软件坏了,自己用python写了一个,分享一下,亲测可用,可以写个监听IP变化自动更新DDNS{仅限腾讯(DDNSPOD)DDNS}。
[Python] 纯文本查看 复制代码
"""
************************************
Description:
Author: ...
Github: [url=https://github.com/jianala]https://github.com/jianala[/url]
Date: 2022-05-25 17:01:33
FilePath: Administrator\Desktop\ddns_dnspod.py
LastEditors: @话痨
LastEditTime: 2022-05-25 17:08:06
善始者实繁,克终者盖寡。
************************************
"""
import requests
import json
from requests.adapters import HTTPAdapter
import logging
import time
import os
from threading import Thread
logging.basicConfig(filemode='a',filename=os.path.join(os.path.dirname(__file__),'ddns.log'),level=logging.INFO,format='%(asctime)s %(message)s',datefmt='%Y-%m-%d %H:%M:%S',encoding='utf8')
s = requests.session()
s.mount('https://', HTTPAdapter(max_retries=5)) # 超时重传次数
login_token = 'id,token'
domain_id = 'domain_id'
ip_list = ["one"]
# curl 'https://dnsapi.cn/Domain.List' -d 'login_token=<login_token>&format=json' 获取domain_id
record_id = ''
def getRecordID():
"""
获取record_id
"""
global record_id
logging.info("获取dns记录ing,可能会卡主")
url = 'https://dnsapi.cn/Record.List'
formdata = {
'domain_id': domain_id,
'login_token': login_token
}
try:
login = s.post(url=url, data=formdata, timeout=2)
except requests.exceptions.RequestException:
logging.info("请求超时,请重试")
rs = login.json()
if rs.get('records'):
record_id = rs['records'][0]['id']
logging.info("获取dns记录完毕")
else:
raise SystemError('获取dns记录失败')
def getIP():
"""
获取IP地址
"""
logging.info("获取iping")
url = "http://www.3322.org/dyndns/getip"
IPInfo = requests.get(url)
IPInfo.encoding = 'UTF-8'
ip = IPInfo.text
logging.info("获取ip完毕")
return ip
def check_ip():
"""
检测IP地址是否变化
"""
ip = getIP().strip()
ip_list.append(ip)
pop_ip = ip_list.pop(0)
time.sleep(900) # 15分钟检测一次
if pop_ip != 'one' and pop_ip != ip_list[0]:
return True
else:
return False
def start_once_ddns():
"""
程序第一次运行执行一次
"""
url = 'https://dnsapi.cn/Record.Ddns'
getRecordID()
ip = getIP().strip()
formdata = {
'domain_id': domain_id,
'login_token': login_token,
'record_line': '默认',
'record_line_id': '10=1',
'value': ip,
'record_id': record_id
}
try:
rs = s.post(url=url, data=formdata, timeout=2)
except requests.exceptions.RequestException:
logging.info("首次请求超时,请重试!")
if (json.loads(rs.text)['status']['code'] == '1'):
message = json.loads(rs.text)['status']['message'], '域名解析已更改为' + ip
logging.info(str(message))
else:
logging.info("首次操作失败")
def updateRecord():
"""
循环监听IP变化,如果IP改变则更新记录
"""
global ip_list
while True:
if check_ip():
logging.info("更改解析ing,可能会卡住")
url = 'https://dnsapi.cn/Record.Ddns'
formdata = {
'domain_id': domain_id,
'login_token': login_token,
'record_line': '默认',
'record_line_id': '10=1',
'value': ip_list[0],
'record_id': record_id
}
try:
rs = s.post(url=url, data=formdata, timeout=2)
except requests.exceptions.RequestException:
getRecordID() # 如果失败,可能是因为record_id被删除或者过期,重新获取
logging.info("请求超时,请重试!")
if (json.loads(rs.text)['status']['code'] == '1'):
message = json.loads(rs.text)['status']['message'], '域名解析已更改为' + ip_list[0]
logging.info(str(message))
else:
logging.info("操作失败")
if __name__ == '__main__':
t1 = Thread(target=start_once_ddns)
t1.start()
t1.join()
updateRecord()
|