How to use awk command in shell to monitor network card traffic in real time
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.