import os
import requests
import json
# Cloudflare API 配置
API_KEY = ' '
ZONE_ID = ' '
RECORD_ID = ' '
DOMAIN_NAME = 'lianchuliu.com'
IP_FILE = 'last_ip.txt'
# 获取当前公网IP
def get_current_ip():
try:
response = requests.get('https://ifconfig.me/ip')
return response.text.strip()
except requests.RequestException as e:
print(f"Error getting current IP: {e}")
return None
# 读取保存的IP
def read_saved_ip():
if os.path.exists(IP_FILE):
with open(IP_FILE, 'r') as file:
return file.read().strip()
return '0.0.0.0'
# 保存IP到文件
def save_ip(ip):
with open(IP_FILE, 'w') as file:
file.write(ip)
# 更新Cloudflare DNS记录
def update_cloudflare_dns(new_ip):
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'
}
data = {
'type': 'A',
'name': DOMAIN_NAME,
'content': new_ip,
'ttl': 120,
'proxied': False
}
try:
response = requests.put(url, headers=headers, data=json.dumps(data))
response.raise_for_status()
print(f"DNS record updated successfully to {new_ip}")
except requests.RequestException as e:
print(f"Error updating DNS record: {e}")
def main():
saved_ip = read_saved_ip()
current_ip = get_current_ip()
if current_ip and current_ip != saved_ip:
update_cloudflare_dns(current_ip)
save_ip(current_ip)
else:
print("IP address has not changed.")
if __name__ == "__main__":
main()
|
|