#!/bin/bash # Bandwidth usage script # Ted Percival 2007 # bash is required to get 64-bit arithmetic # # Use this however you like. http://creativecommons.org/licenses/publicdomain/ # # This script is publicly accessible, currently from # http://lazypants.org/~ted/bwusag set -e # Config options IFACE=eth0 CACHEDIR=$HOME/.cache # These two hold the interface byte counter values CACHE_RX_FILE=$CACHEDIR/bwusag-rx CACHE_TX_FILE=$CACHEDIR/bwusag-tx # These two hold the calculated actual usage for use when the machine reboots CACHE_RXUSAGE_FILE=$CACHEDIR/bwusag-usage-rx CACHE_TXUSAGE_FILE=$CACHEDIR/bwusag-usage-tx TZ=Australia/Brisbane LANG=en_AU.UTF-8 # End config options # Make sure we can find ifconfig PATH=/sbin:$PATH export LANG TZ CUR_RX=`ifconfig $IFACE | grep '^ *RX bytes' | cut -d: -f2 | cut -d' ' -f1` CUR_TX=`ifconfig $IFACE | grep ' TX bytes:' | cut -d: -f3 | cut -d' ' -f1` if [ "$1" = "newmonth" ]; then echo $CUR_RX > $CACHE_RX_FILE echo $CUR_TX > $CACHE_TX_FILE fi START_RX=`cat $CACHE_RX_FILE` START_TX=`cat $CACHE_TX_FILE` if test $(( $CUR_RX - $START_RX )) -lt 0; then # Machine has been rebooted, adjust the counters to compensate START_RX=-`cat $CACHE_RXUSAGE_FILE` START_TX=-`cat $CACHE_TXUSAGE_FILE` # Update stored values echo $START_RX > $CACHE_RX_FILE echo $START_TX > $CACHE_TX_FILE fi # Update the usage byte counter echo $(( $CUR_RX - $START_RX )) > $CACHE_RXUSAGE_FILE echo $(( $CUR_TX - $START_TX )) > $CACHE_TXUSAGE_FILE USED_RX_MB=$((( $CUR_RX - $START_RX ) / 1024 / 1024 )) USED_TX_MB=$((( $CUR_TX - $START_TX ) / 1024 / 1024 )) USED_RX_GB=$(( $USED_RX_MB / 1024 )) USED_TX_GB=$(( $USED_TX_MB / 1024 )) TOTAL_USAGE_MB=$(( $USED_RX_MB + $USED_TX_MB )) TOTAL_USAGE_GB=$(( $TOTAL_USAGE_MB / 1024 )) echo "$TOTAL_USAGE_GB GiB" echo "$TOTAL_USAGE_MB MiB" echo echo "Up: $USED_TX_GB GiB, Down: $USED_RX_GB GiB" echo "Up: $USED_TX_MB MiB, Down: $USED_RX_MB MiB" echo #echo "Updated: `date -R`" uptime exit 0