patschi

OpenVZ Traffic Logger with MySQL in PHP

Mar 24th, 2013
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.07 KB | None | 0 0
  1. <?php
  2.  
  3. mysql_connect("", "", "");
  4. mysql_select_db("");
  5.  
  6. $ips = array();
  7. $cts = array();
  8.  
  9. $data = shell_exec("vzlist -H -o ctid,ip");
  10. $data = explode("\n", $data);
  11. foreach($data as $key => $value) {
  12.     $value = trim($value);
  13.     $value = explode(" ", $value);
  14.     if(!empty($value[0]) && !empty($value[1])) {
  15.         $cts[] = $value[0];
  16.         $ips[] = $value[1];
  17.     }
  18. }
  19.  
  20. //print_r($cts);
  21. //print_r($ips);
  22. //die();
  23.  
  24. $i = 0;
  25. foreach($ips as $ip) {
  26.     $traffic = shell_exec("iptables -nvx -L FORWARD | grep '".$ip."' | tr -s [:blank:] | cut -d' ' -f3| awk '{sum+=$1} END {print sum;}'");
  27.     mysql_query("insert into traffic(ctid, ip, measuringtime, bytes) values('".$cts[$i]."', '".$ip."', '".date("Y-m-d H:i:s")."', '".$traffic."')");
  28.     shell_exec("iptables -D FORWARD -s ".$ip." >/dev/null 2>&1");
  29.     shell_exec("iptables -D FORWARD -d ".$ip." >/dev/null 2>&1");
  30.     shell_exec("iptables -A FORWARD -s ".$ip." >/dev/null 2>&1");
  31.     shell_exec("iptables -A FORWARD -d ".$ip." >/dev/null 2>&1");
  32.     echo "[".$cts[$i]."] ".$ip.": ".$traffic;
  33.     $i++;
  34. }
  35.  
  36. // Empty counter
  37. //shell_exec("iptables -Z");
  38.  
  39. ?>
Advertisement
Add Comment
Please, Sign In to add comment