Simple bandwith monitoring with iptables/xt_quota2

Add some iptables rules without a target:

iptables -t mangle -I PREROUTING -i ppp0 -m quota2 --grow --name incoming
iptables -t mangle -I POSTROUTING -o ppp0 -m quota2 --grow --name outgoing

The quota2 match counts traffic as packets pass this rule, and makes the value available through procfs. This makes it superior to everything that tries to grep and interpret the output of `iptables -L`.

This can easily be wired up with rrdtool to produce some graphs. The following snippet contains the script that should be run every 60 seconds from cron.

#!/bin/bash

q="/proc/net/xt_quota";
file="$HOME/internet.rrd";
if [[ ! -f "$file" ]]; then
    rrdtool create "$file" --step 60 \
        DS:incoming:COUNTER:120:0:U \
        DS:outgoing:CONUTER:120:0:U \
        RRA:AVERAGE:0.5:2:$[60*24*180] \
        RRA:MAX:0.5:2:$[60*24*180] \
        RRA:LAST:0.5:2:$[60*24*180]
fi;

now=$(date +%s);
in=$(cat "$q/incoming");
out=$(cat "$q/outgoing");
rrdtool update "$file" "$now:$in:$out";

The final graph picture can then be produced:

file="$HOME/internet.rrd";
type="AVERAGE";
rrdtool graph "$HOME/internet.png" --start -86400 \
    -a PNG -t "Interface ppp0" -v "Bytes/s" \
    -w 800 -h 400 -M \
    "DEF:x_incoming=$file:incoming:$type" \
    "DEF:x_outgoing=$file:outgoing:$type" \
    "CDEF:y_outgoing=x_outgoing,-1,*" \
    "AREA:x_incoming#008800:Received" \
    "AREA:y_outgoing#880000:Transmitted"

Posted 2009-02-24 01:02 / Tags: Iptables, Linux, Monitoring. / link