DEVTRENCH.COM

cPanel Bandwidth Checking Script

I've been pretty frustrated with the way that cPanel notifies (or doesn't notify) me of bandwidth overages. Seems sometimes I get them and sometimes not. So when I found out that you can do this with the WHM XML api I wanted to get it set up ASAP. This script can be used along with cron and PHPMailer to notify you of the bandwidth usage for all your domains in WHM. I have mine set up to notify me daily so I can keep track of my bandwidth usage.

key-setup
To get your Access key for WHM, login and select Setup Remote Access Key.

If you need more help with the WHM XML API, you can find it here. You can download PHPMailer here.

Bandwidth

";

foreach ($user as $v)
{

  $query = "https://".$v[2].":2087/xml-api/showbw";

  $curl = curl_init();																												# Create Curl Object
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);																# Allow certs that do not match the domain
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);																# Allow self-signed certs
  curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);																# Return contents of transfer on curl_exec
  $header[0] = "Authorization: WHM $v[0]:" . preg_replace("'(\r|\n)'","",$v[1]);	# Remove newlines from the hash
  curl_setopt($curl,CURLOPT_HTTPHEADER,$header);															# Set curl header
  curl_setopt($curl, CURLOPT_URL, $query);																		# Set your URL
  $result = curl_exec($curl);																									# Execute Query, assign to $result
  if ($result == false) {
    error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");
  }
  curl_close($curl);

  $xml = new SimpleXMLElement($result);

$output .= "

".$v[2]."

"; $output .= " "; $output .= ' '; $output .= ' '; $output .= ' '; $output .= ' '; $output .= ' '; foreach($xml->bandwidth[0] as $acct) { if (isset($acct->limit)) { $limit = $acct->limit; $mbs = floatval($limit)/(1024*1024); $total = $acct->totalbytes; $percent = round((floatval($total)/floatval($limit))*100); $warn = ($percent >= 90) ? 'style="background:#F00;color:#FFF;font-weight:bold"' : ''; if($percent>=90) { $color = '#f00'; } elseif($percent>=75) { $color = '#FFE900'; } else { $color = '#00E70A'; } $output .= " "; $output .= ' '; $output .= ' '; $output .= ' '; $output .= ' '; $output .= ' '; } } $output .= "
DomainLimitPercent
' . $acct->maindomain . '' . $mbs . 'MB' . $percent . '%
"; } include_once('class.phpmailer.php'); $mail=new PHPMailer(); $mail->From = $email; $mail->FromName = $email_name"; $mail->Subject = 'Bandwidth Usage for ' . date('D M d, Y'); $mail->MsgHTML($output); $mail->AddAddress($email, $email_name); if(!$mail->Send()) { echo 'Failed to send mail'; } ?>