使用 CloudFlare API 和 PHP 从 CloudFlare 中删除过时的 IP 块

Removing Aged IP Blocks From CloudFlare with CloudFlare API and PHP

我想定期清理 CloudFlare 帐户中设置的超过(比如说)一个月的 IP 地址块。

我当然可以使用 API 下载所有现有 IP 块的完整列表,然后解析在截止日期之前添加的任何块。

我已经开始在 PHP 中对此进行编码,并且意识到这是一项艰巨的任务。在我继续这条路之前,有没有办法在单个 API 调用中完成此操作。

或者有其他方法可以简化这个过程吗?

太!

在此处找到一些 PHP 代码和有关如何执行此操作的说明:

http://www.aetherweb.co.uk/automatically-expiring-cloudflare-ip-blocks-by-age/

逐字粘贴代码:

// Read in all existing CloudFlare IP blocks then delete 
// all which are older than some specified value

$authemail = "your_cloudflare@email_address.com";
$authkey   = "your_cloudflare_auth_key";
$page      = 1;
$ids       = array(); // id's to block
$cutoff    = time()-(3600*24*28); // 28 days

while(1)
{
    $ch = curl_init("https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules?mode=block&configuration_target=ip&page=$page&per_page=10&order=created_on&direction=asc&match=all");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'X-Auth-Email: '.$authemail,
        'X-Auth-Key: '.$authkey,
        'Content-Type: application/json'
        ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);

    $r = json_decode($response, true);

    $result = $r['result'];

    // Scan for results which were created BEFORE $cutoff
    foreach ($result as $block)
    {
        // Only remove 'block' type rules
        // And not if 'donotexpire' is in the notes
        // for the rule
        if (($block['mode'] == 'block') and (!preg_match("/donotexpire/is",$block['notes'])))
        {
            $blocktime = strtotime($block['created_on']);
            if ($blocktime <= $cutoff)
            {
                $ids[] = $block['id'];
            }
        }
    }

    $info   = $r['result_info'];
    // Result info tells us how many pages in total there are
    $page++;
    if ($info['total_pages'] < $page)
    {
        break;
    }
}

$log = '';

foreach ($ids as $id)
{
    // Delete this rule
    $ch = curl_init("https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules/$id");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'X-Auth-Email: '.$authemail,
        'X-Auth-Key: '.$authkey,
        'Content-Type: application/json'
        ));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);

    $log .= $response . "\n";
}

if (sizeof($ids)>0)
{
    mail($authemail, "CF UNBLOCK REPORT " . date('r'), $log);
}