Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

请大佬添加cloudflare.com dns 需求 #71

Open
logdns opened this issue Mar 6, 2020 · 3 comments
Open

请大佬添加cloudflare.com dns 需求 #71

logdns opened this issue Mar 6, 2020 · 3 comments

Comments

@logdns
Copy link

logdns commented Mar 6, 2020

请添加cloudflare.com dns 需求

域名都在CF哦

@ai80233407
Copy link

手撸出了一个, au.sh 你调一下就ok了

@ai80233407
Copy link

`<?php
/**

########## 配合 cerbot 运行 ###################

第一个参数是 action,代表 (add/clean)

第二个参数是 域名

第三个参数是 主机名

第四个参数是 TXT 记录值

第五个参数是 cloudflare 账号邮箱

第六个参数是 cloudflare API秘钥中的 Global API Key

echo "域名 API 调用开始\n";

print_r($argv);
if (count($argv) < 7) {
echo "参数有误\n";
exit;
}

echo $argv[1]."-".$argv[2]."-".$argv[3]."-".$argv[4]."-".$argv[5]."-".$argv[6]."\n";
$cloudflare = new CloudFlareDns($argv[5], $argv[6], $argv[2]);
switch ($argv[1]) {
case "clean":
$data = $cloudflare->deleteDNSrecord($argv[3]);
if (!$data) {
echo "cloudflare dns 域名删除失败-";
exit;
}
break;

case "add":
    $data = $cloudflare->addDNSrecord('txt', $argv[3], $argv[4]);
    if (!$data) {
        echo "cloudflare dns 域名增加失败-";
        exit;
    }
    break;

}

echo "域名 API 调用结束\n";

class CloudFlareDns
{

private $api;
private $email;
private $api_key;
private $zone_id;
private $host;
private $domain;

public function __construct($mail, $api_key, $domain)
{
	$api = [ 			
		"X-Auth-Email: $mail",
		"X-Auth-Key: $api_key",
		'Content-Type: application/json'
	];
	$this->email = $mail;
	$this->api_key = $api_key;
	$this->domain = $domain;
	$this->api = $api;
	$this->host = 'https://api.cloudflare.com/';
	$this->setZone($this->domain);
}

public function setZone($host_name)
{
	$this->zone_id = $this -> getZoneID($host_name);
}

public function getZoneID($host_name) 
{
	/* SENDING RESPONSE */
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "{$this->host}client/v4/zones?name={$host_name}");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $this -> api);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	$content  = curl_exec($ch);
	curl_close($ch);
	/* PARSING RESPONSE */
	$response = json_decode($content,true);
	/* RETURN */
	return $response['result'][0]['id'];
}

public function listDNSrecords()
{
    /* SENDING RESPONSE */
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "{$this->host}client/v4/zones/".$this->zone_id."/dns_records/");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $this -> api);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    $content  = curl_exec($ch);
    curl_close($ch);
    /* PARSING RESPONSE */
    $response = json_decode($content,true);
    $return = [];
    if($response['success'] == true){
        /* RETURN */
        for($i = 0; $i < count($response['result']); $i++) {
            $return[$i] = [
                "id" => $response['result'][$i]['id'],
                "type" => $response['result'][$i]['type'],
                "name" => $response['result'][$i]['name'],
                "proxied" => $response['result'][$i]['proxied'],
                "ttl" => $response['result'][$i]['ttl']
            ];
        }
        return $return;
    }else{
        return false;
    }
}

public function getInfoDNS($name) 
{	
	/* SENDING RESPONSE */
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "{$this->host}client/v4/zones/".$this->zone_id."/dns_records?name={$name}.{$this->domain}");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $this -> api);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	$content  = curl_exec($ch);
	curl_close($ch);
	/* PARSING RESPONSE */
	$response = json_decode($content,true);
	$return = [];
	if (!empty($response['result'])) {
		$return = [
			"id" => $response['result'][0]['id'],
			"type" => $response['result'][0]['type'],
			"name" => $response['result'][0]['name'],
			"data" => $response['result'][0]['data'] ?? [],
			"content" => $response['result'][0]['content'],
			"proxied" => $response['result'][0]['proxied'],
			"ttl" => $response['result'][0]['ttl']
		];
	}
	/* RETURN */
	return $return;
}

public function renameRecord($old_name,$new_name)
{
	$info = $this -> getInfoDNS($old_name);
	$info['data']['name'] = $new_name; //for srv records
	$update = $this -> updateDNSrecord($info['id'],$info['type'],$new_name,$info['content'],$info['data'],$info['ttl'],$info['proxied']);
	return $update;	
}

public function updateDNSrecord($dns_id,$type,$name,$content_v,$data = null,$ttl = 1,$cloudflare_proxy = false)
{	
	/* PARSING RESPONSE */
	$ch = curl_init(); 		
	$payload = json_encode( array( "type"=> $type, "name" => $name, "content" => $content_v, "data" => $data, "ttl" => $ttl, "proxied" => $cloudflare_proxy ) );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
	curl_setopt($ch, CURLOPT_URL, "{$this->host}client/v4/zones/".$this->zone_id."/dns_records/".$dns_id);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
	curl_setopt($ch, CURLOPT_HTTPHEADER, $this -> api);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);		
	$content  = curl_exec($ch);
	curl_close($ch);
	/* PARSING RESPONSE */
	$response = json_decode($content,true);
	/* RETURN */
	if($response['success'] == true)
		return true;
	else
		return false;
}

public function addDNSrecord($type, $name, $content, $ttl = 1, $cloudflare_proxy = false)
{	
	/* PARSING RESPONSE */
	$ch = curl_init();		
	$payload = json_encode(  array( "type"=> $type, "name" => $name, "content" => $content, "ttl" => $ttl, "proxied" => $cloudflare_proxy ));
	curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
	curl_setopt($ch, CURLOPT_URL, "{$this->host}client/v4/zones/".$this->zone_id."/dns_records/");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $this -> api);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	$content  = curl_exec($ch);
	curl_close($ch);
	/* PARSING RESPONSE */
	$response = json_decode($content,true);
	print_r($response);
	/* RETURN */
	if(!empty($response['success']))
		return true;
	else
		return false;
}

public function deleteDNSrecord($name)
{	
	/* PARSING RESPONSE */	
	$info = $this -> getInfoDNS($name);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "{$this->host}client/v4/zones/".$this->zone_id."/dns_records/".$info['id']);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
	curl_setopt($ch, CURLOPT_HTTPHEADER, $this -> api);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	$content  = curl_exec($ch);
	curl_close($ch);
	/* PARSING RESPONSE */
	$response = json_decode($content,true);
	
	/* RETURN */
	if($response['success'] == true)
		return true;
	else
		return false;
}

public function test()
{

	/* PARSING RESPONSE */
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "{$this->host}client/v4/user/tokens/verify");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	$header = [
		"Authorization: Bearer " . CF_TOKEN,
		"Content-Type:application/json"
	];
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	$content  = curl_exec($ch);
	curl_close($ch);
	/* PARSING RESPONSE */
	$response = json_decode($content,true);

	/* RETURN */
	if($response['success'] == true)
		return true;
	else
		return false;
}

}`

@ai80233407
Copy link

`# coding:utf-8

import json
import sys
import os

class CloudflareDns:
def init(self, access_email, access_key_id, domain_name):
self.host = 'https://api.cloudflare.com/'
self.access_email = access_email
self.access_key_id = access_key_id
self.domain_name = domain_name
self.zone_id = self.GetZoneId(domain_name)

def curl(self, url, data, method):
    if sys.version_info[0] < 3:
        print ("s")
        import urllib2
        from urllib2 import URLError, HTTPError
        httpdata = json.dumps(data).encode('utf-8')
        req = urllib2.Request(url=url, data=httpdata)
        req.get_method = lambda: method
        req.add_header('accept', 'application/json')
        req.add_header('Content-Type', 'application/json')
        req.add_header('X-Auth-Email', self.access_email)
        req.add_header('X-Auth-Key', self.access_key_id)
        try:
            with urllib2.urlopen(req) as res:
                code = res.getcode()
                print (res.info())
                resinfo = res.read().decode('utf-8')
                result = True
                if code != 200:
                    result = False
                return (result, json.loads(resinfo))
        except AttributeError as e:
            #python2 处理 PATCH HTTP 方法的一个Bug,不影响结果
            return (True,'')
        except (HTTPError, URLError) as e:
            return (False, str(e))

    else :
        import urllib.request
        from urllib.error import URLError, HTTPError

        httpdata = json.dumps(data).encode('utf-8')

        req = urllib.request.Request(url=url, data=httpdata, method=method)
        req.add_header('accept', 'application/json')
        req.add_header('Content-Type', 'application/json')
        req.add_header('X-Auth-Email', self.access_email)
        req.add_header('X-Auth-Key', self.access_key_id)
        try:
            with urllib.request.urlopen(req) as res:
                code = res.getcode()
                # print (res.info())
                resinfo = res.read().decode('utf-8')
                result = True
                if code != 200:
                    result = False
                return (result, json.loads(resinfo))
        except (HTTPError, URLError) as e:
            return (False, str(e))

def GetZoneId(self, host_name):
    url = self.host + "client/v4/zones?name=" + host_name
    res =  self.curl(url, {}, "GET")
    return res[1]['result'][0]['id']

def SetZone(self, host_name):
    self.zone_id = self.GetZoneId(host_name)

def CreateDNSRecord(self, name, content, recordType='txt', ttl=1, is_proxy=False):
    url = self.host + "client/v4/zones/" + self.zone_id + "/dns_records/"
    data = {"type": recordType, "name": name, "content": content, "ttl": ttl, "proxied": is_proxy}
    res = self.curl(url, data, "POST")
    return res

def GetDNSRecord(self, name):
    url = self.host + "client/v4/zones/" + self.zone_id + "/dns_records?name=" + name + "." + self.domain_name
    res = self.curl(url, {}, "GET")
    return res[1]['result'][0]

def DeleteDNSRecord(self, name):
    info = self.GetDNSRecord(name)
    url = self.host + "client/v4/zones/" + self.zone_id + "/dns_records/" + info['id']
    res = self.curl(url, {}, "DELETE")
    return res

if name == 'main':

print("域名 API 调用开始")
file_name, cmd, certbot_domain, acme_challenge, certbot_validation, ACCESS_EMAIL, ACCESS_KEY_ID = sys.argv
domain = CloudflareDns(ACCESS_EMAIL, ACCESS_KEY_ID, certbot_domain)
# print (domain.GetDNSRecord(selfdomain))
if cmd == "add":
    print(domain.CreateDNSRecord(acme_challenge, certbot_validation))
elif cmd == "clean":
    print (domain.DeleteDNSRecord(acme_challenge))
print("域名 API 调用结束")`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants