cloudflare IP优选 并自动解析到cloudflare(Python实现)
import requests
import json
from datetime import datetime, timedelta

# Cloudflare API 参数
api_token = "zone_id"
zone_id = "api_token"
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():
    response = requests.post("https://www.wetest.vip/api/cf2dns/get_cloudflare_ip", json={
        "key": "o1zrmHAF",
        "type": "v4"
    })
    if response.status_code == 200:
        data = response.json()
        if data.get("status") and "info" in data:
            return data["info"]  # 返回 info 字段中的数据
    return None

# 添加 DNS 记录
def add_dns_record(ip):
    data = {
        "type": "A",
        "name": domain,
        "content": ip,
        "ttl": 1,
        "proxied": False
    }
    response = requests.post(api_url, headers=headers, json=data)
    return response.json()

# 删除 DNS 记录
def delete_dns_record(record_id):
    response = requests.delete(f"{api_url}/{record_id}", headers=headers)
    return response.json()

# 获取现有 DNS 记录
def get_existing_dns_records():
    response = requests.get(api_url, headers=headers)
    return response.json()

# 根据线路代码获取全称
def get_line_name(code):
    line_names = {
        "CM": "移动",
        "CU": "联通",
        "CT": "电信"
    }
    return line_names.get(code, code)  # 返回全称或原始代码

# 格式化输出 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 = (datetime.utcfromtimestamp(ip_entry['uptime']) + timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S')
            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):
    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)
    return response.json()

# 主程序
def main():
    # 获取并删除现有 DNS 记录
    existing_records = get_existing_dns_records()
    if existing_records['success']:
        for record in existing_records['result']:
            if record['name'] == domain and record['type'] == 'A':
                print(f"删除旧的 IP: {record['content']}")
                delete_response = delete_dns_record(record['id'])

    # 获取新的 Cloudflare IP
    cloudflare_data = get_cloudflare_ips()

    # 打印 cloudflare_data 来调试
    print("Cloudflare 数据:", json.dumps(cloudflare_data, indent=4, ensure_ascii=False))  # 格式化输出响应内容

    # 检查返回的数据是否包含 IP 信息
    if cloudflare_data and any(key in cloudflare_data for key in ['CM', 'CU', 'CT']):
        ip_info = cloudflare_data
        if ip_info:
            # 添加标题和格式化 IP 信息
            title = "以下是获取到的 IP 信息:\n"
            header = "线路名称\t优选地址\t网络带宽\t峰值速度\t往返延迟\t数据中心\t更新时间\n"
            formatted_info = format_ip_info(ip_info)
            message = title + header + "\n".join(formatted_info)

            # 发送消息到 Telegram
            send_response = send_to_telegram(message)
            print("Telegram 推送响应:", send_response)

            # 遍历每个运营商的 IP 地址并添加到 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)
        else:
            print("没有获取到 IP 地址信息")
    else:
        print("获取 Cloudflare IP 失败或返回格式不符合预期:", cloudflare_data)

if __name__ == "__main__":
    main()
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇