Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to use awk command in shell to monitor network card traffic in real time

Shulou Source: shulou.com Published: 2022-06-01 14:59:36 09月11日 Update

This article shows you how to use awk commands in shell to monitor network card traffic in real time. The content is concise and easy to understand, which can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

The principle of implementation:

[chengmo@localhost ~] $cat / proc/net/dev

Inter- | Receive | Transmit

Face | bytes packets errs drop fifo frame compressed multicast | bytes packets errs drop fifo colls carrier compressed

Lo:1068205690 1288942839 0 0 0 1068205690 1288942839 0 0 0

Eth0:91581844 334143895 0 0 0 145541676 4205113078 3435231517 0 0 0

The proc/net/dev file stores the total traffic information of the network card and adds up the incoming and outgoing records at intervals. You get the actual rate before subtracting it.

Program code:

The code is as follows:

Awk 'BEGIN {

OFMT= ".3f"

Devf= "/ proc/net/dev"

While (("cat" devf) | getline)

{

If ($0 ~ /: / & & ($1080) > 0)

{

Split ($1dytarr, ":")

Net [tarr [1]] = $10+tarr [2]

Print tarr [1], $10+tarr [2]

}

}

Close (devf)

While ((system ("sleep 1")) > = 0)

{

System ("clear")

While (getline

< devf ) { if($0 ~ /:/ && ($10+0) >

0)

{

Split ($1dytarr, ":")

If (tarr [1] in net)

{

Print tarr [1], ":", ($10+tarr [2]-net [tarr [1]]) * 8Maple 1024, "kb/s"

Net [tarr [1]] = $10+tarr [2]

}

}

}

Close (devf)

}

}'

Note: the first while is to get the total initial value, $1 is the network card outbound traffic, $10 is the network card inbound traffic. The second while starts at intervals of 1 second. The average flow per second is obtained by calculating the total flow difference.

Note: reading the file line by line through getline requires close to close. Otherwise, the data cannot be obtained in the second while loop.

Running result:

The above is how to use awk commands in shell to monitor network card traffic in real time. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Traffic network cards commands real-time monitoring code content total traffic skills files knowledge concise concise information principles practice that is data articles more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Linux OPPO Reno Docker Redmi