Traffic stats per network port
iptables can give you statistics about how many each rule was triggered, so you can add LOG rules on the ports of interest (lets say port 20 & port 80):
iptables -A INPUT -p tcp --dport 22
iptables -A INPUT -p tcp --dport 80
and then
iptables -n -L -v
will give you number of packets and bytes sent through this ports. Of course you will have to parse from the output the ports that interests you.
If you need exact values, add an -x:
iptables -n -L -v -x
You can add accounting rules to your iptables configuration. These should occur before you accept ESTABLISHED and RELATED traffic or you will miss counting traffic that passes. To count web traffic try a rule like:
iptables -A INPUT -p tcp --dport 80
If you have a bunch of them you may want to create an accounting chain so you can report and zero counters on it in isolation from other chains.
The Shorewall firewall allows you to easily add accounting rules to your rule set.
Do not forget to include output traffic statistics.
# Port 80 (HTTP).
iptables -A INPUT -p tcp --dport 80
iptables -A OUTPUT -p tcp --sport 80
# Port 443 (HTTPS).
iptables -A INPUT -p tcp --dport 443
iptables -A OUTPUT -p tcp --sport 443
iptables -n -L -v
iptables -n -L -v -x
iptables -n -L -v -x | grep -i "Chain\|:443\|:80"
Chain INPUT (policy DROP 357 packets, 22828 bytes)
1286265 75076978 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80
1305378 75018232 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:443
Chain OUTPUT (policy ACCEPT 303516 packets, 94716311 bytes)
442 255112 tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp spt:80
46 10515 tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp spt:443