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: