How to measure data transfer across a network interface related to a specifc user

monitoring

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.

Best Answer

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

iptables -I OUTPUT -m owner --uid-owner 1000 -j CONNMARK --set-mark 1
iptables -I INPUT -m mark --mark 1
iptables -I INPUT -j CONNMARK --restore-mark

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 with CONNMARK set 0x1 on the end.

Details:

iptables -I OUTPUT -m owner --uid-owner 1000 -j CONNMARK --set-mark 1

This tells iptables to set firewall mark 1 on all outbound traffic from user with uid=1000.

iptables -I INPUT -j CONNMARK --restore-mark

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).

iptables -I INPUT -m mark --mark 1

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.

Related Topic