Linux top network usage

18 Commands to Monitor Network Bandwidth on Linux server

Network monitoring on Linux

This post mentions some linux command line tools that can be used to monitor the network usage.

These tools monitor the traffic flowing through network interfaces and measure the speed at which data is currently being transferred. Incoming and outgoing traffic is shown separately.

Some of the commands, show the bandwidth used by individual processes. This makes it easy to detect a process that is overusing network bandwidth.

The tools have different mechanisms of generating the traffic report.

Some of the tools like nload read the «/proc/net/dev» file to get traffic stats, whereas some tools use the pcap library to capture all packets and then calculate the total size to estimate the traffic load.

Here is a list of the commands, sorted by their features.

Now lets take a look at each of the commands and how to use them to monitor network usage:

1. Nload

Nload is a commandline tool that allows users to monitor the incoming and outgoing traffic separately.

It also draws out a graph to indicate the same, the scale of which can be adjusted. Easy and simple to use, and does not support many options.

So if you just need to take a quick look at the total bandwidth usage without details of individual processes, then nload will be handy.

Installing Nload — Fedora and Ubuntu have got it in the default repos. CentOS users need to get nload from Epel repositories.

2. iftop

Iftop measures the data flowing through individual socket connections, and it works in a manner that is different from Nload.

Iftop uses the pcap library to capture the packets moving in and out of the network adapter, and then sums up the size and count to find the total bandwidth under use.

Although iftop reports the bandwidth used by individual connections, it cannot report the process name/id involved in the particular socket connection.

But being based on the pcap library, iftop is able to filter the traffic and report bandwidth usage over selected host connections as specified by the filter.

The n option prevents iftop from resolving ip addresses to hostname, which causes additional network traffic of its own.

Install iftop — Ubuntu/Debian/Fedora users get it from default repos. CentOS users get it from Epel.

3. iptraf

Iptraf is an interactive and colorful IP Lan monitor. It shows individual connections and the amount of data flowing between the hosts. Here is a screenshot

4. nethogs

Nethogs is a small ‘net top’ tool that shows the bandwidth used by individual processes and sorts the list putting the most intensive processes on top.

In the event of a sudden bandwidth spike, quickly open nethogs and find the process responsible. Nethogs reports the PID, user and the path of the program.

Install Nethogs — Ubuntu, Debian, Fedora users get from default repos. CentOS users need Epel

5. bmon

Bmon (Bandwidth Monitor) is a tool similar to nload that shows the traffic load over all the network interfaces on the system. The output also consists of a graph and a section with packet level details.

Install Bmon — Ubuntu, Debian and Fedora users can install from default repos. CentOS users need to setup repoforge, since its not available in Epel.

Bmon supports many options and is capable of producing reports in html format. Check the man page for more information

6. slurm

Slurm is ‘yet’ another network load monitor that shows device statistics along with an ascii graph. It supports 3 different styles of graphs each of which can be activated using the c, s and l keys. Simple in features, slurm does not display any further details about the network load.

7. tcptrack

Tcptrack is similar to iftop, and uses the pcap library to capture packets and calculate various statistics like the bandwidth used in each connection.

It also supports the standard pcap filters that can be used to monitor specific connections.

Install tcptrack — Ubuntu, Debian and Fedora have it in default repos. CentOS users need to get it from RepoForge as it is not available in Epel either.

Читайте также:  Приложение для лекций windows

8. Vnstat

Vnstat is bit different from most of the other tools. It actually runs a background service/daemon and keeps recording the size of data transfer all the time.

Next it can be used to generate a report of the history of network usage.

Running vnstat without any options would simply show the total amount of data transfer that took place since the date the daemon is running.

To monitor the bandwidth usage in realtime, use the ‘-l’ option (live mode). It would then show the total bandwidth used by incoming and outgoing data, but in a very precise manner without any internal details about host connections or processes.

Vnstat is more like a tool to get historic reports of how much bandwidth is used everyday or over the past month. It is not strictly a tool for monitoring the network in real time.

Vnstat supports many options, details about which can be found in the man page.

9. bwm-ng

Bwm-ng (Bandwidth Monitor Next Generation) is another very simple real time network load monitor that reports a summary of the speed at which data is being transferred in and out of all available network interfaces on the system.

If the console size is sufficiently large, bwm-ng can also draw bar graphs for the traffic using the curses2 output mode.

Install Bwm-NG — On CentOS bwm-ng can be installed from Epel.

10. cbm — Color Bandwidth Meter

A tiny little simple bandwidth monitor that displays the traffic volume through network interfaces. No further options, just the traffic stats are display and updated in realtime.

11. speedometer

Another small and simple tool that just draws out good looking graphs of incoming and outgoing traffic through a given interface.

12. Pktstat

Pktstat displays all the active connections in real time, and the speed at which data is being transferred through them.

It also displays the type of the connection, i.e. tcp or udp and also details about http requests if involved.

13. Netwatch

Netwatch is part of the netdiag collection of tools, and it too displays the connections between local host and other remote hosts, and the speed at which data is transferring on each connection.

14. Trafshow

Like netwatch and pktstat, trafshow reports the current active connections, their protocol and the data transfer speed on each connection. It can filter out connections using pcap type filters.

Monitor only tcp connections

15. Netload

The netload command just displays a small report on the current traffic load, and the total number of bytes transferred since the program start. No more features are there. Its part of the netdiag.

16. ifstat

The ifstat reports the network bandwidth in a batch style mode. The output is in a format that is easy to log and parse using other programs or utilities.

Install ifstat — Ubuntu, Debian and Fedora users have it in the default repos. CentOS users need to get it from Repoforge, since its not there in Epel.

17. dstat

Dstat is a versatile tool (written in python) that can monitor different system statistics and report them in a batch style mode or log the data to a csv or similar file. This example shows how to use dstat to report network bandwidth

18. collectl

Collectl reports system statistics in a style that is similar to dstat, and like dstat it is gathers statistics about various different system resources like cpu, memory, network etc.

Over here is a simple example of how to use it to report network usage/bandwidth.

Summary

Those were a few handy commands to quickly check the network bandwidth on your linux server. However these need the user to login to the remote server over ssh.

Alternatively web based monitoring tools can also be used for the same task.

Ntop and Darkstat are some of the basic web based network monitoring tools available for Linux.

Beyond these lie the enterprise level monitoring tools like Nagios that provide a host of features to not just monitor a server but entire infrastructure.

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

88 thoughts on “ 18 Commands to Monitor Network Bandwidth on Linux server ”

Amazing Article, Really useful information to all So, I hope you will share more information to be check and share here.thanks for sharing.

Читайте также:  Cashcode mvu драйвер linux

Thanks for sharing this amazing informative article. this is best for cs students mainly linux student to know about these commands.

Wow, so much loads of usefulness! Thank you for this! Lots of tools I never heard and surprise they are there by default on reposity, just apt install away!!

Based on nethogs, there’s a Qt software providing charts per application:
https://slist.lilotux.net/linux/nethogs-qt/index_en.html

thanks for mentioning.

Very informative and useful article. We can see all the commands at one shot.

Thanks for sharing

it is really a great article and helping to learn about Linux network.
Keep sharing such great knowledge

These are perfect 100% working commands. That is quite amazing. Thanks for such a useful article…

Great article.It’s a big collection for monitor, is any app can track daily bandwidth ?

Thanks! Nethogs is perfect for me as it shows usage per process: current bandwith and total used, great!

Thanks, it is saving a lot of time

Very informative and useful article.
Thanks for sharing

that was really useful
thanks

Thanks for sharing informative article I have been looking for these command with step by step guide you did a great job and i found a solution that I am looking for keep up the good work.

You are right.
Actually i was too looking about this commands.
At least i found these all here.
Thanks.

This commands its very helpful for me i want to i want to know how to create a server 2012 r2 in home

20+ year vet here. pure gold .. many of these are new to me.
excellent article

glad that you liked it.
thanks for the comment.

Very good and useful compilation.
Good job and thanks!!

Now an article about _graphical_ monitor network applications would be even better 🙂

This a gem for commands.
Thanks 🙂

Thank you for this article, I didn’t know about these tools.

Thank you, very good article, a treasure trove 🙂

In our company we are several clients which are connected to an Ubuntu Server. Sometimes there is problem in entire network of company and we have heavy load on server. We try to find which client causes this problem.
As part of solution should be monitored entire network 24 hour per day? And if yes, which network monitoring tool helps us to find bad client and how to log it to analyze later?
How can we get complete status of each client and its transaction with our server? For example, a client named A have connection with server, how can we see how many bandwidths is used by this client?

Use a proper router like opnsense. It can monitor per host traffic and even put quotas on certain hosts or otherwise profile them to use less bandwidth.

Thank you. We can see all the commands at one shot.

Great article. Thanks for all you have done here. Very good examples and a good read. Exceptionally useful information.

Источник

TOP’ай сюда

Обзор практически всех *top утилит под linux (atop, iotop, htop, foobartop и т.д.).

Все мы знаем top — самую простую и самую распространённую утилиту из этого списка. Показывает примерно то же, что утилита vmstat, плюс рейтинг процессов по потреблению памяти или процессора. Совсем ничего не знает про загрузку сети или дисков. Позволяет минимальный набор операций с процессом: renice, kill (в смысле отправки сигнала, убийство — частный случай). По имени top суффикс «-top» получили и все остальные подобные утилиты в этом обзоре.


Atop имеет два режима работы — сбор статистики и наблюдение за системой в реальном времени. В режиме сбора статистики atop запускается как демон и раз в N времени (обычно 10 мин) скидывает состояние в двоичный журнал. Потом по этому журналу atop’ом же (ключ -r и имя лог-файла) можно бегать вперёд-назад кнопками T и t, наблюдая показания atop’а с усреднением за 10 минут в любой интересный момент времени.

В отличие от top отлично знает про существование блочных устройств и сетевых интерфейса, способен показывать их загрузку в процентах (на 10G, правда, процентов не получается, но хотя бы показывается количество мегабит).

Незаменимое средство для поиска источников лагов на сервере, так как сохраняет не только статистику загрузки системы, но и показатели каждого процесса — то есть «долистав» до нужного момента времени можно увидеть, кто этот счастливый момент с LA > 30 создал. И что именно было причиной — IO программ, своп (нехватка памяти), процесор или что-то ещё. Помимо большего количества информации ещё способен двумя цветами подсказывать, какие параметры выходят за разумные пределы.


В отличие от atop, htop не собирает статистику и просто показывает текущее состояние. Второе яркое отличие — нортоноподобная панелька с подсказками кнопок снизу и возможность «навигации» по списку процессов.

Читайте также:  Что такое центр предварительной оценки windows

Поддерживает выделение процессов и выполнения над ними групповых операций (впрочем, с форк бомбой им не справиться).

Общей статистике по системе показыват мало (зато с шкалой а-ля прогресс-бар), зато имеет обширнейшие инструменты для анализа процессов, включая баловство с скедулингом (приоритеты, affinity), просмотр списка открытых файлов, strace и массу мелких, но приятных фич, таких как контекстный поиск по имени процесса, режим «слежения» за процессом, быстрые операции с процессом и т.д.

iotop


Специализированная утилита для анализа потребления дисковой полосы. К сожалению, не показывает иопсы (это вообще возможно?) Благодаря показу kernel threads способен указать на kcopy/swapper/kflush как источник хруста винта (чего не может atop). Заодно показывает общую загруженность IO системы в Мб/с (чего так же не может atop). Довольно быстрый.

iftop


Опять же, специализированная утилита, позволяющая наблюдать за трафиком в реальном времени. Требует очень рутовых прав и pcap, т.к. работает почти аналогичо tcpdump’у. Показывает загруженность интерфейса (поддерживается только один интерфейс в одной копии), направления трафика и интенсивность трафика.

На средне-загруженном сервере, который внезапно начал жрать инет позволяет очень быстро найти направление, в которое идёт больше всего трафика (в любую сторону). К сожалению, не показывает распределение трафика по процессам.

powertop


Специализированная (ага, снова) утилита от intel для мониторинга потребления мощности (электрической мощности!) разными процессами. В реальности никаких ваттов не показывает, а показывает время, затраченное на обслуживание процессором. Уникальна тем, что показывает прерывания и прочие события ядра на одном уровне с процессами (что позволяет находить нетривиальные ситуации перегрузки сервера и даже определять, от какой железки это исходит). При равной нагрузке позволяет оценить, чей драйвер шустрее работает.

Кроме того, во вкладке device stats позволяет оценить степень загруженности устройства (точнее, драйвера устройства). Для сетевых карт (включая виртуальные, типа tun) показывает pps (packets per seconds).

Во вкладке idle status показывает распределение состояний процессора (C1, C2, C3), что весьма полезно при выяснении «батарейка дохлая или что-то не так с системой?» на ноутбуках.


Ну очень специализированная утилита для мониторинга прерываний (настоящих прерываний, идентификацией их по номеру).

kerneltop

Наверное, должен показывать что-то интересное про ядро. У меня дома ему не понравился System.map, а на сервере — отсутствие /proc/profile.

dnstop


Специализированный анализатор DNS-трафика на интерфейсе. Наверное, был бы очень полезен при починке DNS на контроллере домена, к сожалению, Active Directory на линуксе работает не очень хорошо.

Безусловно полезно для нахождения засранца, загоняющего бинд в неприличный LA.

jnettop

Почти клон iftop, однако имеет забавный режим, когда может слушать соседей и показывать top по их трафику. Не очень работает в эпоху коммутаторов.

Ещё умеет агрегацию адресов (так, чтобы показывать их трафик одной строкой).

sntop

Замечательная штука для скринсейвера или публичного монитора — по конфигу рассылает пинги и показывает, если какой-то хост лёг. В принципе, в рабочих условиях при настроенном конфиге позволяет быстро оценить состояние не очень большого парка серверов (запустили — и сразу красным видно, кто лежит).

latencytop

Я бы с интересом на него посмотрел, но оно требует особого конфига ядра…

xrestop


Монитор потребления ресурсов X-сервера разными приложениями, которые к нему подключились. (Обнаружил, что хром жрёт ресурсов х-сервера много больше, чем опера).

slabtop


Специализируется на структурах данных SLAB ядра, фактически, показывает использование памяти в более тонких категориях, чем «свободно/занято/кеш». View only, несколько режимов сортировки.

Software specific

apachetop

Не столь полезен, как хотелось бы, показывает статистику ответов на запросы. Никакой магии, просто читает логи апача.

sqtop

Топ по логам сквида. С учётом скорости их роста, сначала генерирует промежуточную статистику, а потом уже даёт по ней шариться.

pg_top

Пакет в debian почему-то называется ptop. Мониторит загрузку postgresql.

mytop


Мониторит mysql. Есть альтернативный mtop, делает примерно то же, но заброшен и (в дебиане) выпилен в районе lenny -> squeeze.

xentop


Мониториг доменов xen’а. Интересен тем, что показывает не только память-процессор, но и дисковые операции с сетью. К сожалению, никакого управления, view only. Единственный из всех top’ов, не влазящий в 80 столбцов при выводе.

Список топов, которые я глазами не посмотрел:

hatop — мониторинг haproxy
virt-top — мониторинг за работой libvirt
mctop — мониторинг состояния memcached
perf-top — нашёл документацию, самого perf-top в виде тарбола или пакета не нашёл.

offTOP

Сначала ложные топы кратко:
gkrelmtop — плагин под gkrelm (монитор производительности в гуе) — оффтопик.
ntop — нарушает text-based традицию интерактивных программ и ставится как сайт для апача.
libgtop — библиотека для мониторигна производительности
nload — консольный монитор сетевой активности, в отличие от обычных top’ов не выводит рейтинг, а рисует текстовый график.

А потом настоящие топы без уважительного суффикса ‘top’ в названии.

nethogs


Отображает сетевой трафик от конкретных приложений.

Источник

Оцените статью