Changes

Jump to: navigation, search

Traffic accounting with iptables

1,466 bytes added, 20:14, 25 November 2006
Scripting
echo `iptables -nv -L FORWARD | grep $i | tr -s [:blank:] |cut -d' ' -f3| awk '{sum+=$1} END {print sum;}'` >> $trafficlog
done
# reset the counter
iptables -Z
# update the ip table rules if there is a any change in vz's
./vz-iptables-create-rules
 
# copy the trafficlog file to a webserver where users can take their traffic
# please mind to use
# ssh-keygen -t rsa
# to generate ssh keys
# and append the new public key from your hardware node ~/.ssh/id_rsa.pub
# to ~/.ssh/authorized_keys2 on the HOST-TO-SHOW-THE-TRAFFIC-TO-THE-USERS
scp $trafficlog USER@HOST-TO-SHOW-THE-TRAFFIC-TO-THE-USERS:/var/www/OPENVZ-CONTROL-WEB-SITE/tmp/$HOSTNAME-traffic
# clear the copied trafficlog
cp /dev/null $trafficlog
# start a php script to store the traffic in a MySQL Database on the HOST-TO-SHOW-THE-TRAFFIC-TO-THE-USERS
wget -q http://HOST-TO-SHOW-THE-TRAFFIC-TO-THE-USERS/login/traffic-read.php?HN=$HOSTNAME -O /dev/null
</pre>
 
a small sample php script to store the trafficlog in a MySQL Database on the HOST-TO-SHOW-THE-TRAFFIC-TO-THE-USERS
<pre>
<?
$MySQL_Host="INSERT-YOUR-MYSQL-HOST-HERE";
$MySQL_User="INSERT-YOUR-MYSQL-USER-HERE";
$MySQL_Passw="INSERT-YOUR-MYSQL-PASSWORD-HERE";
mysql_connect("$MySQL_Host","$MySQL_User","$MySQL_Passw");
 
$HN=trim(addslashes($_GET["HN"])); // Hardware Node
 
$handle = fopen ("tmp/$HN","r");
while (!feof($handle)) {
$line = fgets($handle, 4096);
list($date,$time,$ip,$traffic)=explode(" ",$line);
if($traffic>0) {mysql($db,"insert into Traffic (ip,measuringtime,bytes) values('$ip','$date $time','$traffic')");}
}
fclose($handle);
</pre>
 
You can use crontab to run this script once per hour or day to collect your traffic statistics.
22
edits

Navigation menu