The way I do it is with two firewall rules that just accumulate the incoming and outgoing byte counts and a script that reads and resets those counts every hour, logging a cumulative result to a file. The rules go in the mangle table:
Code:
iptables -t mangle -A PREROUTING ! -s 192.168.0.0/16 -i eth1
iptables -t mangle -A POSTROUTING ! -d 192.168.0.0/16 -o eth1
The exclusion for 192.168.0.0/16 is so that traffic to and from the modem's internal web server is not counted. That traffic never goes out on the cable.
Here's the script that runs each hour. I also have a trigger that runs it when the interface is shut down so that I don't miss the final, partial hour.
Code:
#!/bin/bash
Ddir=/srv/log
unset Sudo
[ $(id -u) != 0 ] && Sudo=sudo
declare -a Pzero Pcnt
# A bit messy. Timestamps in the file are local time, but the reset
# occurs at midnight UTC at the end of each month.
Reset=n
if [ -s $DDir/netcount ]; then
Pzero=($(tail -1 $DDir/netcount))
# Convert local timestamp to seconds since 1/1/1970 00:00:00 UTC
Tsec=$(date -d "${Pzero[0]} ${Pzero[1]}" +%s)
# Compare that UTC month with current UTC month
[ $(date -u -d @$Tsec +%m) != $(date -u "+%m") ] && Reset=y
else
Pzero=(mm/dd/yy hh:mm:ss 0 0 0 0)
fi
Pcnt=( $($Sudo /sbin/iptables -t mangle -vnxL -Z | awk '
/PREROUTING/ { dir = "in"; }
/POSTROUTING/ { dir = "out"; }
/ eth[01] / { count[dir] = $2; }
END { print count["in"], count["out"]; }') )
if [ ${#Pcnt[*]} != 2 ]; then
echo "Bad counts (${#Pcnt[*]}) from iptables. Pcnt=(${Pcnt[*]})" >&2
exit 1
fi
date "+%x %X ${Pcnt[0]} ${Pcnt[1]} $((${Pzero[4]}+${Pcnt[0]})) $((${Pzero[5]}+${Pcnt[1]}))" >>$DDir/netcount
[ $Reset = y ] && date -d "now + 1 second" "+%x %X 0 0 0 0" >>$DDir/netcount
That's actually a fragment from a larger script -- apologies if I missed something when extracting it. If the script is to be run from a non-root UID, then you need a NOPASSWD rule in /etc/sudoers to allow it.
Here's an excerpt from that log file, taken around the end of a month:
Code:
11/30/14 16:00:01 2729527 1100269 25212875259 968153775
11/30/14 17:00:01 297509 65356 25213172768 968219131
11/30/14 18:00:01 1008185 98442 25214180953 968317573
11/30/14 18:00:02 0 0 0 0
11/30/14 19:00:02 273945 64896 273945 64896
11/30/14 20:00:01 3312753 476234 3586698 541130
Each entry shows the
in and
out counts for the current hour plus the cumulative totals for the current month.