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
| import requests import time import logging import subprocess import re
logging.basicConfig( filename="/root/DdnsOnCloudFlare/ddns.log", level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", )
ZONE_ID='209367eb6xxxx67741f291252' RECORD_NAME='pan.xinhaojin.top' API_KEY='zRImW_Rxxxxxx_ecoRTzeXKR4'
def get_ipv4_address(): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" } url = "https://tool.lu/ip/" try: response = requests.get(url, headers=headers, timeout=10) if response.status_code == 200: pattern = re.compile(r'你的外网IP地址是:([0-9.]+)</p>') match = pattern.search(response.text) if match: ip_address = match.group(1) return ip_address else: logging.error("未找到包含 IP 地址的信息") else: logging.error(f"请求失败,状态码: {response.status_code}") except Exception as e: logging.error(f"发生异常: {e}")
def get_ipv6_address(): try: result = subprocess.run( ["ip", "-6", "addr", "show", "enp3s0"], capture_output=True, text=True, ) lines = result.stdout.splitlines() for line in lines: if "240e" in line: return line.strip().split()[1].split("/")[0] except Exception as e: logging.error(f"获取 IPv6 地址失败: {e}") return None
def list_records(zone_id, record_name, api_key, record_type): try: url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records" headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} params = {"name": record_name, "type": record_type} response = requests.get(url, headers=headers, params=params, timeout=10) response.raise_for_status() data = response.json() if data["success"]: return [ (record["id"], record["content"]) for record in data["result"] ] except requests.RequestException as e: logging.error(f"获取 {record_type} 记录失败: {e}") return []
def delete_record(zone_id, api_key, record_id): url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{record_id}" headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} try: response = requests.delete(url, headers=headers) response.raise_for_status() data = response.json() if data["success"]: logging.info(f"记录删除成功 (ID: {record_id})") return True except requests.RequestException as e: logging.error(f"删除记录失败 (ID: {record_id}): {e}") return False
def create_record(zone_id, record_name, api_key, record_type, value): url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records" headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} payload = { "type": record_type, "name": record_name, "content": value, "ttl": 600, "proxied": False, } try: response = requests.post(url, headers=headers, json=payload, timeout=10) response.raise_for_status() data = response.json() if data["success"]: logging.info(f"{record_type} 记录创建成功 (值: {value})") return True except requests.RequestException as e: logging.error(f"创建记录失败 ({record_type}, {value}): {e}") return False
def update_record(zone_id, record_name, api_key, record_type, current_ip): try: records = list_records(zone_id, record_name, api_key, record_type) found = False if len(records) >= 1: for record_id, record_value in records: if record_value == current_ip: found = True logging.info(f"{record_type} 记录值匹配,无需更新 (值: {record_value})") else: logging.info(f"{record_type} 记录值不同,删除旧记录 (当前值: {record_value})") delete_record(zone_id, api_key, record_id) time.sleep(3) if not found: logging.info(f"未找到匹配的 {record_type} 记录,正在创建新记录...") return create_record(zone_id, record_name, api_key, record_type, current_ip) except Exception as e: logging.error(f"更新记录函数发生异常: {e}") return False
def main(): try: while True: ipv4 = get_ipv4_address() ipv6 = get_ipv6_address()
if ipv4: logging.info(f"获取到的外部 IPv4 地址为: {ipv4}") update_record(ZONE_ID, RECORD_NAME, API_KEY, "A", ipv4) else: logging.error("无法获取 IPv4 地址")
if ipv6: logging.info(f"获取到的外部 IPv6 地址为: {ipv6}") update_record(ZONE_ID, RECORD_NAME, API_KEY, "AAAA", ipv6) else: logging.error("无法获取 IPv6 地址") time.sleep(300) except Exception as e: logging.error(f"主循环中发生异常: {e}")
if __name__ == "__main__": main()
|