Table of Contents

Ubuntu - Networking - Measure the amount of data that is sent by a server to the outside

Problem

We want to measure the amount of data that is sent by a server to the outside (to the Internet), but the device is in the DMZ-or a local network.

Assuming:

If, whilst on the server, we used some networking commands to try to obtain this measurement, these commands will actually increase that total.

So to get a true figure of the Server only, we need to subtract any other data in the same network range.


Solution

One of many solutions:

Add the following iptables rules:

iptables -t mangle -I POSTROUTING -d ! 192.168.1.0/24
iptables -t mangle -I POSTROUTING 2 -d 127.0.0.1

NOTE: The firewall rules do not have to (j …) as they only update a counter (available with the command:

iptables -t mangle -v -S or iptables -t mangle -L -v)
  • The first rule catches all outgoing packets to a network other than the Server (in the example 192.168.1.0/24).
  • The second rule captures packets sent to the address 127.0.0.1. This would be the Server.

NOTE: Subtract the first value from the of the other, which does the following script:

nettraffic.sh
#!/bin/bash
#
R1="\-A POSTROUTING -d ! 192.168.1.0/24"
R2="\-A POSTROUTING -d 127.0.0.1"
 
RES_NOT_LAN=$( iptables -t mangle -S POSTROUTING -v | grep "$R1" )
RES_LO=$( iptables -t mangle -S POSTROUTING -v | grep "$R2" )
TOTAL_NOT_LAN=$( echo "$RES_NOT_LAN" | awk '{ print $NF }')
TOTAL_LO=$( echo "$RES_LO" | awk '{ print $NF }')
 
TOTAL=$(( $TOTAL_NOT_LAN - $TOTAL_LO ))
 
echo $TOTAL