1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
| import requests import os import sys import datetime import platform import subprocess import re
cf_email_addr = "" cf_global_api_key = "" domain_main = "" domain_full_ddns = "" record_type = "AAAA"
eth_card = "" ip_index = "local"
reset_ip = 0 enable_cache = 0 skip_connectivity_check = 0 ip_file = "ip.txt" id_file = "cloudflare.ids" log_file = "cloudflare.log"
example_config_file = { "cf_email_addr": "", "cf_global_api_key": "", "domain_main": "", "domain_full_ddns": "", "record_type": "", "eth_card": "", "ip_index": "local", "reset_ip": 0, "enable_cache": 0, "skip_connectivity_check": 0, "ip_file": "ip.txt", "id_file": "cloudflare.ids", "log_file": "cloudflare.log" }
def log(message): """日志函数""" if message: if enable_cache == 1: with open(log_file, 'a') as f: f.write(f"[{datetime.datetime.now()}] - {message}\n") else: print(f"[{datetime.datetime.now()}] - {message}")
def init_value(): global cf_email_addr, cf_global_api_key, domain_main, domain_full_ddns, record_type, eth_card, skip_connectivity_check, ip_index, reset_ip, enable_cache, ip_file, id_file, og_file config_dict = {} script_dir = os.path.dirname(os.path.abspath(__file__)) config_path = os.path.join(script_dir, "config.txt") try: with open(config_path, 'r', encoding='utf-8') as file: for line in file: line = line.strip() if line and '=' in line: key, value = line.split('=', 1) config_dict[key] = value common_keys = set(config_dict.keys()) & set(example_config_file.keys()) different_values = {} for key in common_keys: if config_dict[key] != example_config_file[key]: different_values[key] = (config_dict[key], example_config_file[key]) if len(different_values) == 0: print(f"请将该配置文件填写完成:{config_path}") sys.exit() log("File config.txt exists.") cf_email_addr = config_dict.get('cf_email_addr') cf_global_api_key = config_dict.get('cf_global_api_key') domain_main = config_dict.get('domain_main') domain_full_ddns = config_dict.get('domain_full_ddns') record_type = config_dict.get('record_type') eth_card = config_dict.get('eth_card') ip_index = config_dict.get('ip_index') reset_ip = int(config_dict.get('reset_ip')) enable_cache = int(config_dict.get('enable_cache')) skip_connectivity_check = int(config_dict.get('skip_connectivity_check')) ip_file = config_dict.get('ip_file') id_file = config_dict.get('id_file') log_file = config_dict.get('log_file') except FileNotFoundError: with open(config_path, 'w', encoding='utf-8') as file: for key, value in example_config_file.items(): file.write(f'{key}={value}\n') print(f"请将该配置文件填写完成:{config_path}") sys.exit()
def get_ipv6_address_windows(): """在Windows上获取临时IPv6地址""" try: output = subprocess.check_output(["ipconfig"], text=True) match = re.search(r"临时 IPv6 地址.*: ([a-fA-F0-9:]+)", output) if match: return match.group(1) else: return None except Exception as e: print(f"Error: {e}") return None
def get_ipv6_address_linux(): """在Linux上获取Global IPv6地址""" try: output = subprocess.check_output(["ip", "-6", "addr", "show", eth_card], text=True) match = re.search(r"inet6\s+([a-fA-F0-9:]+)/\d+\s+scope global", output) if match: return match.group(1) else: return None except Exception as e: print(f"Error: {e}") return None
def get_ipv6_platform(): if platform.system() == "Windows": return get_ipv6_address_windows() elif platform.system() == "Linux": return get_ipv6_address_linux() else: return None
def get_ip(): """获取IP地址""" if record_type == "AAAA": if reset_ip == 1: log("Reset DDNS address to loopback...") return "::1" elif reset_ip == 2: ip = input("Please enter an AAAA record IP:\n") log("Got it, now setting DDNS...") return ip else: if ip_index == "internet": return requests.get('https://api64.ipify.org?format=json').json()['ip'] elif ip_index == "local": return get_ipv6_platform() pass elif record_type == "A": if reset_ip == 1: log("Reset DDNS address to loopback...") return "127.0.0.1" elif reset_ip == 2: ip = input("Please enter an A record IP:\n") log("Got it, now setting DDNS...") return ip else: if ip_index == "internet": return requests.get('https://api.ipify.org?format=json').json()['ip'] elif ip_index == "local": pass else: log("Error DNS type") exit(0)
def update_cloudflare_dns(ip): """更新Cloudflare DNS记录""" headers = { "X-Auth-Email": cf_email_addr, "X-Auth-Key": cf_global_api_key, "Content-Type": "application/json", } zone_response = requests.get(f"https://api.cloudflare.com/client/v4/zones?name={domain_main}", headers=headers) zone_id = zone_response.json()['result'][0]['id']
dns_response = requests.get(f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records?type={record_type}&name={domain_full_ddns}", headers=headers) dns_record_id = dns_response.json()['result'][0]['id']
data = { "type": record_type, "name": domain_full_ddns, "content": ip, "ttl": 1, "proxied": False } update_response = requests.put(f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{dns_record_id}", headers=headers, json=data) return update_response.json()
log("Init config") init_value() log("Starting DDNS") if skip_connectivity_check == 0: log("Checking connectivity to cloudflare") try: response = requests.get("https://api.cloudflare.com", timeout=30) if response.ok: log("Successfully connected to https://api.cloudflare.com") else: log("Connected to https://api.cloudflare.com but received a non-success status code:", response.status_code) except requests.exceptions.RequestException as e: log("Error connecting to https://api.cloudflare.com") log(e) sys.exit() except requests.exceptions.Timeout: log("Timeout connecting to https://api.cloudflare.com") log(e) sys.exit() log("Check Initiated") else: log("Skipping check connectivity to Cloudflare")
ip = get_ip() log(f"Your ip is: {ip}")
old_ip = None if enable_cache == 1 and os.path.exists(ip_file): with open(ip_file) as f: old_ip = f.read().strip() if ip == old_ip: if ip == None: log("Check your Internet connection.") else: log("IP has not changed.") exit(0)
update_result = update_cloudflare_dns(ip) if update_result['success']: message = f"Now {domain_full_ddns} -> {ip}" if enable_cache == 1: with open(ip_file, 'w') as f: f.write(message) log(message) else: message = f"API UPDATE FAILED. DUMPING RESULTS:\n{update_result}" log(message) exit(1)
|