1

I'm using a Linux box as a router between two of its network interfaces to route local traffic to and from the internet. The internet connection in question has a defined data allowance, and exceeding this is expensive.

Ideally, I'd like to have the Linux box monitor the amount of data being transferred over the internet-facing interface (as the sum of received and transmitted data) and to bring the interface down once that limit is exceeded. I've been unable to find a ready-made tool for this purpose. How would I best go about this?

Nick Kennedy
  • 131
  • 5

1 Answers1

2

One option is to use a root cron job that runs every minute with the following script (with output appended to a logfile):

#!/bin/bash
USAGE=$(awk '/wlan0/ {print $2+$10}' /proc/net/dev)
USAGEMIB=$(echo "$USAGE" | awk '{printf "%0.1f", $1 / 1024 / 1024}')
LIMIT=500
ABOVELIMIT=$(echo "$USAGEMIB" "$LIMIT"| awk '$1 > $2 {print "1"}')
echo -e $(date)"\t"$USAGE"\t"$USAGEMIB" MiB"
if [ "$ABOVELIMIT" == "1" ]
  then
    echo "Limit reached."
    /sbin/ifdown wlan0
fi

This sums together the received and transferred bytes in the relevant entry in /proc/net/dev, prints it as bytes and MiB to stdout (redirected to a log), and if the usage exceeds the limit that is hardcoded into the file near the top brings down the connection. It's not particularly robust (in particular it doesn't have any error handling), but should serve the purpose intended.

Nick Kennedy
  • 131
  • 5