Skip to content

Instantly share code, notes, and snippets.

@gopi-ar
Created October 30, 2017 07:43
Show Gist options
  • Save gopi-ar/a47c8b3cf6d2fdf12f5e14f40720cc5d to your computer and use it in GitHub Desktop.
Save gopi-ar/a47c8b3cf6d2fdf12f5e14f40720cc5d to your computer and use it in GitHub Desktop.
Count Cloudflare DNS queries For All Domains
<?php
/*
* Script to count DNS queries for each domain associated to Cloudflare Account
*
* Params
* email Cloudflare Email
* token Cloudflare Global API Token
* start Start date in UTC ISO-8601 format Ex: 2017-10-20T00:00:00.000Z
* end End date in UTC ISO-8601 format
* domains (Optional) list of domains to compute DNS totals for; separate with comma. If this is empty, all domains will be checked. Ex: google.com,yahoo.com
* Run
* php cloudflare-dns-analytics.php email=<email> token=<token> start=<start date> end=<end date> domains=<domain1>,<domain2>
*/
//Convert cli params to GET request
if(isset($argv))
{
parse_str(implode('&', array_slice($argv, 1)), $_REQUEST);
}
// Checks whether arguments are set or not
if (!isset($_REQUEST['email'], $_REQUEST['token'], $_REQUEST['start'], $_REQUEST['end']))
{
echo "Error please pass email, key, start and end date as arguments";
exit;
}
$email = "X-Auth-Email: " . $_REQUEST['email'];
$token = "X-Auth-Key: " . $_REQUEST['token'];
$start = $_REQUEST['start'];
$end = $_REQUEST['end'];
$domainsFilter = isset($_REQUEST['domains']) ? explode(",", $_REQUEST['domains']) : null;
print_r($domainsFilter);
$url = "https://api.cloudflare.com/client/v4/zones";
//Gets all Zone ID's associated to the Cloudflare account
echo "Fetching list of zones\n";
$zones = curl($url, $email, $token);
// Converts json to associative array
$zones = json_decode($zones,true);
if(isset($zones, $zones['result']))
{
$countZones = count($zones['result']);
$i = 0;
$totals = array();
foreach ($zones['result'] as $key => $value)
{
$i++;
if (isset($value['id'], $value['name']))
{
// Gets Zone ID
$zone = $value['id'];
// Domain Name associated with the Zone ID
$domain = $value['name'];
if($domainsFilter && !in_array($domain, $domainsFilter)) {
echo "Skipping $domain \n";
continue;
}
echo "Processing $domain $i / $countZones domains\n";
// Gets total DNS query count for each Domain
$totalQueries = dnsQuery($zone, $start, $end, $email, $token);
if(isset($totalQueries))
{
$totals[$domain] = $totalQueries;
}
else
{
//Error, couldn't calculate
$totals[$domain] = -1;
}
}
}
foreach ($totals as $domain => $total) {
echo "$domain Total DNS Queries: $total" . "\n";
}
}
function dnsQuery($zone, $startDate, $endDate, $email, $token)
{
// Setting deafult timezone to UTC since we are using UTC ISO-8601 format
date_default_timezone_set('UTC');
// Converting Date to epoch format
$start = strtotime($startDate);
$total = 0;
while($start < strtotime($endDate))
{
$start = date("Y-m-d H:i:s", $start);
// Converting Date to UTC ISO-8601 format
$since = date("Y-m-d\TH:i:s.000\Z", strtotime($start));
// Incrementing end date by 6 hours
$until = date("Y-m-d\TH:i:s.000\Z", strtotime("{$start}+6 hour"));
$url = "https://api.cloudflare.com/client/v4/zones/{$zone}/dns_analytics/report?metrics=queryCount&sort=&since={$since}&until={$until}&limit=100";
$r = curl($url, $email, $token);
$r = json_decode($r, true);
$subTotal = 0;
if (isset($r['result']['totals']['queryCount']))
{
// Counts total dns queries
$subTotal = $r['result']['totals']['queryCount'];
$total += $subTotal;
}
echo "$start to $until - $subTotal DNS queries. Cumulative - $total DNS queries \r";
// Incrementing start date by 6 hours
$start = date("Y-m-d H:i:s", strtotime("{$start}+6 hour"));
// Converting to epoch format
$start = strtotime($start);
}
return $total;
}
function curl($url, $email, $token)
{
// Initiate the curl session
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, $url);
// Removes the headers from the output
curl_setopt($ch, CURLOPT_HTTPHEADER, array($email, $token, 'Content-Type: application/json'));
// Return the output instead of displaying it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Set timeouts
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
//Follow a redirect
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
//Will show up in remote logs as this
curl_setopt($ch,CURLOPT_USERAGENT,'Unwired Bot');
// Execute the curl session
$output = curl_exec($ch);
return $output;
}
Copy link

ghost commented May 20, 2021

Many thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment