Shellawk implements real-time Nic traffic monitoring script (Common Application 2)

Source: Internet
Author: User
You must be aware of the network card traffic obtained through the 3rd-party tool. In fact, the effects can be achieved through scripts. The following figure shows the data I sorted out in my personal work. The following is a shell script to collect network card traffic

Implementation principle:
[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 0 0 1068205690 1288942839 0 0 0 0 0 0
Eth0: 91581844 334143895 0 0 0 0 0 145541676 4205113078 3435231517 0 0 0 0 0 0

The proc/net/dev file stores the total traffic information of the network adapter. the network adapter and the outgoing record are added up at intervals. The actual rate is obtained after subtraction.

Program code:


Copy codeThe code is as follows:
Awk 'In in {
OFMT = "%. 3f ";
Devf = "/proc/net/dev ";
While ("cat" devf) | getline)
{
If ($0 ~ /:/& ($10 + 0)> 0)
{
Split ($1, tarr ,":");
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 ($1, tarr ,":");
If (tarr [1] in net)
{
Print tarr [1], ":", ($10 + tarr [2]-net [tarr [1]) * 8/1024, "kb/s ";
Net [tarr [1] = $10 + tarr [2];
}
}
}
Close (devf );
}
}'


Note: The first while is to obtain the total initial value. $1 indicates the outbound traffic of the NIC and $10 indicates the inbound traffic of the NIC. 2nd while will be started once every 1 second. Calculate the total traffic difference to get the average traffic per second.

Note: close is required to read files row by row through getline. Otherwise, data cannot be obtained in 2nd while loops.

Running result:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.