通过编写python脚本结合cloudflare api实现公网ip变动检测与自动更新。核心做法是利用requests库获取当前出口ip,并与cloudflare dns记录中的现有ip进行比对,若不一致则调用api执行更新操作。

如何准确获取当前公网IP地址
使用公共HTTP服务如ipify或httpbin.org的JSON接口,解析返回的ip字段即可得到准确的公网IPv4地址。

import requests
def get_public_ip():
try:
response = requests.get("https://api.ipify.org?format=json")
response.raise_for_status()
return response.json()["ip"]
except Exception as e:
print(f"获取IP失败: {e}")
return None
如何安全调用Cloudflare API更新DNS记录
通过Cloudflare Zone API查询指定域名对应的DNS记录ID,比对记录内容与当前IP,仅在IP发生变化时发送PATCH请求进行更新,避免无效请求触发频率限制。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;

import requests
CF_TOKEN = "your_cloudflare_api_token"
ZONE_ID = "your_zone_id"
RECORD_ID = "your_record_id"
DOMAIN = "example.com"
def update_cf_dns(new_ip):
headers = {
"Authorization": f"Bearer {CF_TOKEN}",
"Content-Type": "application/json"
}
# 获取当前记录详情
url = f"https://api.cloudflare.com/client/v4/zones/{ZONE_ID}/dns_records/{RECORD_ID}"
response = requests.get(url, headers=headers)
data = response.json()
if not data.get("success"):
print("获取DNS记录失败")
return
current_ip = data["result"]["content"]
if current_ip == new_ip:
print("IP未变化,无需更新")
return
# 更新DNS记录
payload = {"content": new_ip}
update_response = requests.patch(url, headers=headers, json=payload)
result = update_response.json()
if result.get("success"):
print(f"成功更新DNS记录为: {new_ip}")
else:
print(f"更新失败: {result.get('errors')}")
# 主流程
if __name__ == "__main__":
ip = get_public_ip()
if ip:
update_cf_dns(ip)
如何在检测到IP变动后保持程序持续运行
将上述逻辑封装在循环中,利用time模块设置合理的轮询间隔(如5分钟),确保脚本能长期后台运行并及时响应IP变化。

















