I have an Ubuntu server and I am interested in measuring how much data is being transferred (both in and out) across a network interface, by a specific user. How do I do it?
N.B. I know how to measure the total data transfer of the whole machine. I want to restrict my monitoring to a specific user.
You can use iptables rules to do this. Here are some commands that would keep track of all traffic for a user with UID=1000
You can then view the counters with
iptables -nvL
. The number of bytes is the second field.For input traffic you'll want to look at the line under INPUT that has
mark match 0x1
on the end. For output traffic it'll be the line withCONNMARK set 0x1
on the end.Details:
This tells iptables to set firewall mark
1
on all outbound traffic from user with uid=1000.This tells iptables to use connection tracking to figure out which incoming packets are associated with the outgoing packets, and restore any firewall marks for the stream (ie, the ones that we set the mark on above).
This tells iptables to match any incoming packets that have firewall mark
1
. We dont do anything with them, we just use it so it'll increment the counters.The only way you can really accomplish that is to write your own System Tap script. I did something similar for Zabbix monitoring. The script at the link does not keep track of data per user, but it shows the basic concept.