使用CloudFlare API和PHP从CloudFlare中删除老化的IP块

时间:2016-02-25 11:10:28

标签: php firewall cloudflare

我想定期清理CloudFlare帐户中设置的IP地址块,这些地址块早于(比如说)一个月。

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

我已经开始用PHP编写代码并且意识到这是一项非常重要的任务。在我继续前进之前,有没有办法在单个API调用中执行此操作。

还是有其他方法来简化这个过程吗?

TY!

1 个答案:

答案 0 :(得分:0)

在这里找到一些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);
}