How can I get the current network interface throughput statistics on Linux/UNIX? [closed]
Asked Answered
L

15

113

Tools such as MRTG provide network throughput / bandwidth graphs for the current network utilisation on specific interfaces, such as eth0. How can I return that information at the command line on Linux/UNIX?

Preferably this would be without installing anything other than what is available on the system as standard.

Lvov answered 27/2, 2009 at 20:39 Comment(2)
Consider switching your answer given the iftop details.Wagonette
Too bad this question has been closed, because I wanted to add bmon which is helpful. github.com/tgraf/bmon#screenshotsConni
S
16

You can parse the output of ifconfig

Santasantacruz answered 27/2, 2009 at 20:45 Comment(5)
(usually) You don't need to be root to run this...Pyrotechnic
A bad bash one-liner that does exactly this (and makes me long for BSD netstat(1) behaviour): while true; do export `ifconfig p1p1 | grep packets | awk '{print $5, $3}' | xargs echo | sed -E -e "s/([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)/rx=\1 rxp=\2 tx=\3 txp=\4/"` ; echo $rx $rxp $tx $txp `cat /tmp/netstat` | awk '{print $1-$5, $2-$6, $3-$7, $4-$8}';echo $rx $rxp $tx $txp > /tmp/netstat; sleep 5 ;doneBovid
Parsing ifconfig output is error-prone, for instance the above one-liner results in -bash: export: overruns:0': not a valid identifier` for me on RHEL6. Parsing /sys/class/net/$dev/statistics (see the perl script in @Dualism answer) directly works much better.Hindman
should not be the accepted answer as it's error prone and not practical. there are utilities that do the job much better, Scroll down to find out.Borries
not very useful answer. please give a more detailed (how to be parsed? what info is relevant?)Innis
A
164

iftop does for network usage what top(1) does for CPU usage -- http://www.ex-parrot.com/~pdw/iftop/

I don't know how "standard" iftop is, but I was able to install it with yum install iftop on Fedora.

Actomyosin answered 23/3, 2009 at 17:29 Comment(6)
WOW! Wow wow! This tool produces a live barchart of the top hosts. You can watch all your OpenVPN clients fighting for it in real time. Very cool. ThxGoldi
iftop can be installed on a clean Ubuntu install easily as well: apt-get install iftop.Koan
and on Arch Linux with pacman -S iftopElmiraelmo
sigh Well, I guess this means I'm putting off learning to parse tcpdump output again. Thank you iftop and wireshark, for allowing me to be this lazy.Baras
Note that the question asked for per-interface statistics, but iftop is more detailed, and gives per connection statistics.Seraphim
For those without admin rights, note that iftop requires installation (you won't even be able to build it without libpcap installed) and its homepage says it must be run under root.Hindman
H
115

Got sar? Likely yes if youre using RHEL/CentOS.

No need for priv, dorky binaries, hacky scripts, libpcap, etc. Win.

$ sar -n DEV 1 3
Linux 2.6.18-194.el5 (localhost.localdomain)    10/27/2010

02:40:56 PM     IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s   rxcmp/s   txcmp/s  rxmcst/s
02:40:57 PM        lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00
02:40:57 PM      eth0  10700.00   1705.05 15860765.66 124250.51      0.00      0.00      0.00
02:40:57 PM      eth1      0.00      0.00      0.00      0.00      0.00      0.00      0.00

02:40:57 PM     IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s   rxcmp/s   txcmp/s  rxmcst/s
02:40:58 PM        lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00
02:40:58 PM      eth0   8051.00   1438.00 11849206.00 105356.00      0.00      0.00      0.00
02:40:58 PM      eth1      0.00      0.00      0.00      0.00      0.00      0.00      0.00

02:40:58 PM     IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s   rxcmp/s   txcmp/s  rxmcst/s
02:40:59 PM        lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00
02:40:59 PM      eth0   6093.00   1135.00 8970988.00  82942.00      0.00      0.00      0.00
02:40:59 PM      eth1      0.00      0.00      0.00      0.00      0.00      0.00      0.00

Average:        IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s   rxcmp/s   txcmp/s  rxmcst/s
Average:           lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00
Average:         eth0   8273.24   1425.08 12214833.44 104115.72      0.00      0.00      0.00
Average:         eth1      0.00      0.00      0.00      0.00      0.00      0.00      0.00
Halfmast answered 27/10, 2010 at 19:4 Comment(5)
For kB/s Transmit and Receive: sar -n DEV 1 3 | grep $IFACE | tail -n1 | awk '{print $5, $6}'Lapierre
@Lapierre - minor nit: you meant Receive and Transmit, in that order. :-)Tales
Sar is a lovely old tool. It it another binary or four and assorted cronjobs for collecting, though :)Giraldo
Running Centos7, no sar.Kwang
google.com/webhp?q=sar%20centos%207 ...a quick Google search will turn up lots of information.Autocratic
D
46

I wrote this dumb script a long time ago, it depends on nothing but Perl and Linux≥2.6:

#!/usr/bin/perl

use strict;
use warnings;

use POSIX qw(strftime);
use Time::HiRes qw(gettimeofday usleep);

my $dev = @ARGV ? shift : 'eth0';
my $dir = "/sys/class/net/$dev/statistics";
my %stats = do {
    opendir +(my $dh), $dir;
    local @_ = readdir $dh;
    closedir $dh;
    map +($_, []), grep !/^\.\.?$/, @_;
};

if (-t STDOUT) {
    while (1) {
        print "\033[H\033[J", run();
        my ($time, $us) = gettimeofday();
        my ($sec, $min, $hour) = localtime $time;
        {
            local $| = 1;
            printf '%-31.31s: %02d:%02d:%02d.%06d%8s%8s%8s%8s',
            $dev, $hour, $min, $sec, $us, qw(1s 5s 15s 60s)
        }
        usleep($us ? 1000000 - $us : 1000000);
    }
}
else {print run()}

sub run {
    map {
        chomp (my ($stat) = slurp("$dir/$_"));
        my $line = sprintf '%-31.31s:%16.16s', $_, $stat;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[0]) / 1)
            if @{$stats{$_}} > 0;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[4]) / 5)
            if @{$stats{$_}} > 4;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[14]) / 15)
            if @{$stats{$_}} > 14;
        $line .= sprintf '%8.8s', int (($stat - $stats{$_}->[59]) / 60)
            if @{$stats{$_}} > 59;
        unshift @{$stats{$_}}, $stat;
        pop @{$stats{$_}} if @{$stats{$_}} > 60;
        "$line\n";
    } sort keys %stats;
}

sub slurp {
    local @ARGV = @_;
    local @_ = <>;
    @_;
}

It just reads from /sys/class/net/$dev/statistics every second, and prints out the current numbers and the average rate of change:

$ ./net_stats.pl eth0
rx_bytes                       :  74457040115259 4369093 4797875 4206554 364088
rx_packets                     :     91215713193   23120   23502   23234  17616
...
tx_bytes                       :  90798990376725 8117924 7047762 7472650 319330
tx_packets                     :     93139479736   23401   22953   23216  23171
...
eth0                           : 15:22:09.002216      1s      5s     15s     60s

                                ^ current reading  ^-------- averages ---------^
Dualism answered 27/2, 2009 at 22:40 Comment(2)
I had to replace "8s" and "8.8s" with "16s" and "16.16s" for the numbers to fit.Hindman
If I understand right, to make the final result accurate (for example in live stats), it has to run every second on /proc/net/dev or calculate data on per/second basic somehow else?Premarital
B
41

nload is a great tool for monitoring bandwidth in real time and easily installed in Ubuntu or Debian with sudo apt-get install nload.

Device eth0 [10.10.10.5] (1/2):
=====================================================================================
Incoming:


                               .         ...|    
                               #         ####|   
                           .. |#|  ...   #####.         ..          Curr: 2.07 MBit/s
                          ###.###  #### #######|.     . ##      |   Avg: 1.41 MBit/s
                         ########|#########################.   ###  Min: 1.12 kBit/s
             ........    ###################################  .###  Max: 4.49 MBit/s
           .##########. |###################################|#####  Ttl: 1.94 GByte
Outgoing:
            ##########  ###########    ###########################
            ##########  ###########    ###########################
            ##########. ###########   .###########################
            ########### ###########  #############################
            ########### ###########..#############################
           ############ ##########################################
           ############ ##########################################
           ############ ##########################################  Curr: 63.88 MBit/s
           ############ ##########################################  Avg: 32.04 MBit/s
           ############ ##########################################  Min: 0.00 Bit/s
           ############ ##########################################  Max: 93.23 MBit/s
         ############## ##########################################  Ttl: 2.49 GByte

Another excellent tool is iftop, also easily apt-get'able:

             191Mb      381Mb                 572Mb       763Mb             954Mb     
└────────────┴──────────┴─────────────────────┴───────────┴──────────────────────
box4.local            => box-2.local                      91.0Mb  27.0Mb  15.1Mb
                      <=                                  1.59Mb   761kb   452kb
box4.local            => box.local                         560b   26.8kb  27.7kb
                      <=                                   880b   31.3kb  32.1kb
box4.local            => userify.com                         0b   11.4kb  8.01kb
                      <=                                  1.17kb  2.39kb  1.75kb
box4.local            => b.resolvers.Level3.net              0b     58b    168b
                      <=                                     0b     83b    288b
box4.local            => stackoverflow.com                   0b     42b     21b
                      <=                                     0b     42b     21b
box4.local            => 224.0.0.251                         0b      0b    179b
                      <=                                     0b      0b      0b
224.0.0.251           => box-2.local                         0b      0b      0b
                      <=                                     0b      0b     36b
224.0.0.251           => box.local                           0b      0b      0b
                      <=                                     0b      0b     35b


─────────────────────────────────────────────────────────────────────────────────
TX:           cum:   37.9MB   peak:   91.0Mb     rates:   91.0Mb  27.1Mb  15.2Mb
RX:                  1.19MB           1.89Mb              1.59Mb   795kb   486kb
TOTAL:               39.1MB           92.6Mb              92.6Mb  27.9Mb  15.6Mb

Don't forget about the classic and powerful sar and netstat utilities on older *nix!

Begird answered 9/4, 2014 at 22:32 Comment(1)
this should be the accepted answerBorries
R
33

You could parse /proc/net/dev.

Ribbentrop answered 27/2, 2009 at 20:54 Comment(4)
/proc does not exist on every UNIX.Santasantacruz
True, just assumed due to the Linux tag, that OP was only interested in Linux.Ribbentrop
there is no such file on 3.17 kernelTacita
Seems to be equivalent to parsing /sys/class/net/$dev/statistics as in ephemient's script.Hindman
I
28
  • dstat - Combines vmstat, iostat, ifstat, netstat information and more
  • iftop - Amazing network bandwidth utility to analyse what is really happening on your eth
  • netio - Measures the net throughput of a network via TCP/IP
  • inq - CLI troubleshooting utility that displays info on storage, typically Symmetrix. By default, INQ returns the device name, Symmetrix ID, Symmetrix LUN, and capacity.
  • send_arp - Sends out an arp broadcast on the specified network device (defaults to eth0), reporting an old and new IP address mapping to a MAC address.
  • EtherApe - is a graphical network monitor for Unix modeled after etherman. Featuring link layer, IP and TCP modes, it displays network activity graphically.
  • iptraf - An IP traffic monitor that shows information on the IP traffic passing over your network.

More details: http://felipeferreira.net/?p=1194

Inborn answered 22/11, 2013 at 16:30 Comment(1)
Thanks for the simple list and that these are mostly default utilities. In particular I was able to get very nice peak bandwidth out of iftop without installing anything.Adverb
S
16

You can parse the output of ifconfig

Santasantacruz answered 27/2, 2009 at 20:45 Comment(5)
(usually) You don't need to be root to run this...Pyrotechnic
A bad bash one-liner that does exactly this (and makes me long for BSD netstat(1) behaviour): while true; do export `ifconfig p1p1 | grep packets | awk '{print $5, $3}' | xargs echo | sed -E -e "s/([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)/rx=\1 rxp=\2 tx=\3 txp=\4/"` ; echo $rx $rxp $tx $txp `cat /tmp/netstat` | awk '{print $1-$5, $2-$6, $3-$7, $4-$8}';echo $rx $rxp $tx $txp > /tmp/netstat; sleep 5 ;doneBovid
Parsing ifconfig output is error-prone, for instance the above one-liner results in -bash: export: overruns:0': not a valid identifier` for me on RHEL6. Parsing /sys/class/net/$dev/statistics (see the perl script in @Dualism answer) directly works much better.Hindman
should not be the accepted answer as it's error prone and not practical. there are utilities that do the job much better, Scroll down to find out.Borries
not very useful answer. please give a more detailed (how to be parsed? what info is relevant?)Innis
F
16

I got another quick'n'dirty bash script for that:

#!/bin/bash
IF=$1
if [ -z "$IF" ]; then
        IF=`ls -1 /sys/class/net/ | head -1`
fi
RXPREV=-1
TXPREV=-1
echo "Listening $IF..."
while [ 1 == 1 ] ; do
        RX=`cat /sys/class/net/${IF}/statistics/rx_bytes`
        TX=`cat /sys/class/net/${IF}/statistics/tx_bytes`
        if [ $RXPREV -ne -1 ] ; then
                let BWRX=$RX-$RXPREV
                let BWTX=$TX-$TXPREV
                echo "Received: $BWRX B/s    Sent: $BWTX B/s"
        fi
        RXPREV=$RX
        TXPREV=$TX
        sleep 1
done

It's considering that sleep 1 will actually last exactly one second, which is not true, but good enough for a rough bandwidth assessment.

Thanks to @ephemient for the /sys/class/net/<interface>! :)

Fideicommissary answered 14/6, 2013 at 6:45 Comment(3)
If you want to format your numbers as MB/s, swap out the "echo" line with this: echo $BWRX $BWTX | awk '{ rx = $1 / 1024 / 1024 ; tx = $2 / 1024 / 1024 ; print "Received " rx "MB/s, Sent " tx "MB/s" }'Parlour
@BuddyCasino I'm sure you could do it directly in the let BWRX=($RX-$RXPREV)/1024 (though I don't have anything to test it now)Fideicommissary
It seems you are right, it didn't work for some reason when I tried to do it that way, so I settled for awk, but I guess it was just a typo.Parlour
P
15

Besides iftop and iptraf, also check:

  • bwm-ng (Bandwidth Monitor Next Generation)

and/or

  • cbm (Color Bandwidth Meter)

ref: http://www.powercram.com/2010/01/bandwidth-monitoring-tools-for-ubuntu.html

Paladin answered 7/5, 2010 at 0:0 Comment(2)
bwm-ng rocks: it does not need any special permission to be run.Fenske
I use it for years already and in most use cases I find its interface much clearer than for example iftop's.Dualpurpose
O
8

If you want just to get the value, you can use simple shell oneliner like this:

S=10; F=/sys/class/net/eth0/statistics/rx_bytes; X=`cat $F`; sleep $S; Y=`cat $F`; BPS="$(((Y-X)/S))"; echo $BPS

It will show you the average "received bytes per second" for period of 10 seconds (you can change period by changing S=10 parameter, and you can measure transmitted BPS instead of received BPS by using tx_bytes instead of rx_bytes). Don't forget to change eth0 to network device you want to monitor.

Of course, you are not limited to displaying the average rate (as mentioned in other answers, there are other tools that will show you much nicer output), but this solution is easily scriptable to do other things.

For example, the following shell script (split into multiple lines for readability) will execute offlineimap process only when 5-minute average transmit speed drops below 10kBPS (presumably, when some other bandwidth-consuming process finishes):

#!/bin/sh
S=300; F=/sys/class/net/eth0/statistics/tx_bytes
BPS=999999
while [ $BPS -gt 10000 ]
do
  X=`cat $F`; sleep $S; Y=`cat $F`; BPS="$(((Y-X)/S))";
  echo BPS is currently $BPS
done
offlineimap

Note that /sys/class/... is Linux specific (which is ok as submitter did choose linux tag), and needs non-archaic kernel. Shell code itself is /bin/sh compatible (so not only bash, but dash and other /bin/sh implementations will work) and /bin/sh is something that is really always installed.

Oh answered 20/9, 2014 at 13:10 Comment(0)
N
5

I like iptraf but you probably have to install it and it seems to not being maintained actively anymore.

Neglectful answered 27/2, 2009 at 20:44 Comment(2)
There's an iptraf-ng, any suggestions on differences between them?Lunarian
iptraf-ng is a fork of the original project. It should have all original features with more.Fenske
S
3

I find dstat to be quite good. Has to be installed though. Gives you way more information than you need. Netstat will give you packet rates but not bandwith also. netstat -s

Sesquiplane answered 1/4, 2009 at 2:59 Comment(0)
S
3

You can use iperf to benchmark network performance (maximum possible throughput). See following links for details:

http://en.wikipedia.org/wiki/Iperf

https://iperf.fr/

https://code.google.com/p/iperf/

Shorthanded answered 28/7, 2014 at 20:2 Comment(0)
F
0

I couldn't get the parse ifconfig script to work for me on an AMI so got this to work measuring received traffic averaged over 10 seconds

date && rxstart=`ifconfig eth0 | grep bytes | awk '{print $2}' | cut -d : -f 2` && sleep 10 && rxend=`ifconfig eth0 | grep bytes | awk '{print $2}' | cut -d : -f 2` && difference=`expr $rxend - $rxstart` && echo "Received `expr $difference / 10` bytes per sec"

Sorry, it's ever so cheap and nasty but it worked!

Flue answered 25/11, 2014 at 14:39 Comment(0)
F
0
ifconfig -a
ip -d link
ls -l /sys/class/net/ (physical and virtual devices)
route -n

If you want the output of (ifconfig -a) in json format you can use this (python)

Fart answered 8/12, 2014 at 13:31 Comment(1)
None of these report throughput statistics?Heloise

© 2022 - 2024 — McMap. All rights reserved.