python3利用cloudflare api批量解析域名及配置page rules

首先访问https://dash.cloudflare.com/profile/api-tokens获取Global API Key。

#获取你的账号id
curl -X GET "https://api.cloudflare.com/client/v4/accounts?page=1&per_page=20&direction=desc" \
     -H "X-Auth-Email: 你的邮箱地址" \
     -H "X-Auth-Key: 你的Global API Key" \
     -H "Content-Type: application/json"


import requests
import json

header = {
    'X-Auth-Email': '你的邮箱地址',
    'X-Auth-Key': '你的Global API Key',
    'Content-Type': 'application/json'
}
def getDomainId(domain):
    url = "https://api.cloudflare.com/client/v4/zones?name=" + domain + "&status=active&account.id="你的账号id"&account.name="邮箱"&page=1&per_page=20&order=status&direction=desc&match=all"
    try:
        r = requests.get(url,timeout=30,headers=header)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        domain_id = json.loads(r.text)['result'][0]['id']
        domain_name = json.loads(r.text)['result'][0]['name']
        print(domain_name, domain_id)
        if domain == domain_name:
            return domain_id
        else:
            print("域名不匹配")
    except Exception as e:
        raise e

def post_data(url,data):
    try:
        r = requests.post(url,data,timeout=30,headers=header)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.status_code
    except Exception as e:
        raise e

def main(domain):
    url = "https://api.cloudflare.com/client/v4/zones"
    domain_id = getDomainId(domain)
    url2 = url + "/" + domain_id + "/dns_records"
    print('url: ',url2)
    all_target = "wsall." + domain + ".whecloud.com"
    all_data = '{"type":"CNAME","name":' + "\""  + "*" + "\"" ',"content":' + "\"" + all_target + "\"" + ',"ttl":0,"priority":10,"proxied":false}'
    print(all_target, all_data)
    print(post_data(url2, all_data))
    page_url = url + "/" + domain_id + "/pagerules"
    print(page_url)
    http_data = '{"targets":[{"target":"url","constraint":{"operator":"matches","value":"http://' + domain + '/*"}}],"actions":[{"id":"forwarding_url","value":{"url":"https:\/\/www.' + domain + '\/$1","status_code":301}}],"priority":1,"status":"active"}'
    print(http_data)
    print(post_data(page_url, http_data))

if __name__ == "__main__":
    domain = input("请输入您的域名:")
    main(domain)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值