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



我想定期清理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);
}

最新更新