本文最后更新于 314 天前,其中的信息可能已经有所发展或是发生改变。
import requests
import json
from datetime import datetime, timedelta, timezone
# Cloudflare API 参数
api_token = "api_token"
zone_id = "zone_id"
domain = "domain"
# Telegram Bot 参数
tg_bot_token = "tg_bot_token"
tg_chat_id = "tg_chat_id"
# Cloudflare API 端点
api_url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records"
# 请求头
headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json"
}
# 获取 Cloudflare IP 的接口
def get_cloudflare_ips():
try:
response = requests.post("https://www.wetest.vip/api/cf2dns/get_cloudflare_ip", json={
"key": "o1zrmHAF",
"type": "v4"
}, timeout=30)
if response.status_code == 200:
data = response.json()
if data.get("status") and "info" in data:
return data["info"]
return None
except requests.exceptions.RequestException as e:
print(f"获取 Cloudflare IP 时发生错误: {e}")
return None
# 添加 DNS 记录
def add_dns_record(ip):
data = {
"type": "A",
"name": domain,
"content": ip,
"ttl": 1,
"proxied": False
}
try:
response = requests.post(api_url, headers=headers, json=data, timeout=30)
return response.json()
except requests.exceptions.RequestException as e:
print(f"添加 DNS 记录时发生错误: {e}")
return {"success": False, "errors": [str(e)]}
# 删除 DNS 记录
def delete_dns_record(record_id):
try:
response = requests.delete(f"{api_url}/{record_id}", headers=headers, timeout=30)
return response.json()
except requests.exceptions.RequestException as e:
print(f"删除 DNS 记录时发生错误: {e}")
return {"success": False, "errors": [str(e)]}
# 获取现有 DNS 记录
def get_existing_dns_records():
try:
response = requests.get(api_url, headers=headers, timeout=30)
return response.json()
except requests.exceptions.RequestException as e:
print(f"获取 DNS 记录时发生错误: {e}")
return {"success": False, "errors": [str(e)]}
# 格式化时间戳为北京时间 (UTC+8)
def format_timestamp(timestamp):
"""将时间戳格式化为北京时间"""
# 创建 UTC 时区的时间对象
utc_time = datetime.fromtimestamp(timestamp, timezone.utc)
# 转换为 UTC+8 时区(北京时间)
beijing_timezone = timezone(timedelta(hours=8))
beijing_time = utc_time.astimezone(beijing_timezone)
return beijing_time.strftime('%Y-%m-%d %H:%M:%S')
# 格式化输出 IP 信息
def format_ip_info(ip_info):
results = []
for line_code, ips in ip_info.items():
for ip_entry in ips:
ip = ip_entry['ip']
bandwidth = f"{ip_entry['bandwidth']} MB"
speed = f"{ip_entry['speed']} kB/s"
delay = f"{ip_entry['delay']} 毫秒"
colo = ip_entry['colo']
uptime = format_timestamp(ip_entry['uptime'])
line_name = ip_entry['line_name']
result = f"{line_name}\t{ip}\t{bandwidth}\t{speed}\t{delay}\t{colo}\t{uptime}"
results.append(result)
return results
# 发送消息到 Telegram
def send_to_telegram(message):
try:
url = f"https://api.telegram.org/bot{tg_bot_token}/sendMessage"
data = {
"chat_id": tg_chat_id,
"text": message,
"parse_mode": "Markdown"
}
response = requests.post(url, json=data, timeout=30)
return response.json()
except requests.exceptions.RequestException as e:
print(f"发送 Telegram 消息时发生错误: {e}")
return {"ok": False, "description": str(e)}
# 清理旧的 DNS 记录
def cleanup_old_records():
"""删除指定域名的所有 A 记录"""
existing_records = get_existing_dns_records()
deleted_count = 0
if existing_records.get('success'):
for record in existing_records['result']:
if record['name'] == domain and record['type'] == 'A':
print(f"删除旧的 DNS 记录: {record['content']} (ID: {record['id']})")
delete_response = delete_dns_record(record['id'])
if delete_response.get('success'):
deleted_count += 1
else:
print(f"删除记录失败: {delete_response.get('errors', '未知错误')}")
return deleted_count
# 主程序
def main():
print("开始执行 Cloudflare IP 优选脚本...")
# 清理旧的 DNS 记录
print("清理旧的 DNS 记录...")
deleted_count = cleanup_old_records()
print(f"已删除 {deleted_count} 条旧的 DNS 记录")
# 获取新的 Cloudflare IP
print("获取新的 Cloudflare IP 地址...")
cloudflare_data = get_cloudflare_ips()
if not cloudflare_data:
print("获取 Cloudflare IP 失败")
send_to_telegram("❌ 获取 Cloudflare IP 失败,请检查 API 接口状态")
return
# 打印 cloudflare_data 来调试
print("Cloudflare 数据:", json.dumps(cloudflare_data, indent=4, ensure_ascii=False))
# 检查返回的数据是否包含 IP 信息
if any(key in cloudflare_data for key in ['CM', 'CU', 'CT']):
ip_info = cloudflare_data
added_count = 0
# 添加标题和格式化 IP 信息
title = "✅ Cloudflare IP 优选结果\n"
header = "线路\tIP地址\t带宽\t速度\t延迟\t数据中心\t更新时间\n"
formatted_info = format_ip_info(ip_info)
message = title + header + "\n".join(formatted_info)
# 遍历每个运营商的 IP 地址并添加到 DNS 记录
print("添加新的 DNS 记录...")
for line in ip_info.keys():
for ip_entry in ip_info[line]:
ip = ip_entry['ip']
print(f"添加 IP: {ip}")
add_response = add_dns_record(ip)
if add_response.get('success'):
added_count += 1
print(f"成功添加 IP: {ip}")
else:
print(f"添加 IP 失败: {add_response.get('errors', '未知错误')}")
# 发送消息
print("发送消息到 Telegram...")
summary = f"\n📊 操作记录:\n删除旧记录: {deleted_count} 条\n添加新记录: {added_count} 条"
send_response = send_to_telegram(message + "\n" + summary)
if send_response.get('ok'):
print("Telegram 消息发送成功")
else:
print(f"Telegram 消息发送失败: {send_response.get('description', '未知错误')}")
print(f"脚本执行完成。删除 {deleted_count} 条记录,添加 {added_count} 条记录。")
else:
error_msg = "❌ 获取 Cloudflare IP 失败或返回格式不符合预期"
print(error_msg)
send_to_telegram(error_msg)
if __name__ == "__main__":
main()