linux下shell脚本实时监控网卡流量
通过/proc/net/dev 可以查看到网卡的流量,可以根据该文件中值的变化结合while循环写一个实时监控网卡的脚本,通过指定网卡名为参数来监控指定网卡的流量
#!/bin/bash
while [ "1" ]
do
eth=$1
RXpre=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $2}')
TXpre=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $10}')
sleep 1
RXnext=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $2}')
TXnext=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $10}')
clear
echo -e "t RX `date +%k:%M:%S` TX"
RX=$((${RXnext}-${RXpre}))
TX=$((${TXnext}-${TXpre}))
if [[ $RX -lt 1024 ]];then
RX="${RX}B/s"
elif [[ $RX -gt 1048576 ]];then
RX=$(echo $RX | awk '{print $1/1048576 "MB/s"}')
else
RX=$(echo $RX | awk '{print $1/1024 "KB/s"}')
fi
if [[ $TX -lt 1024 ]];then
TX="${TX}B/s"
elif [[ $TX -gt 1048576 ]];then
TX=$(echo $TX | awk '{print $1/1048576 "MB/s"}')
else
TX=$(echo $TX | awk '{print $1/1024 "KB/s"}')
fi
echo -e "$eth t $RX $TX "
done
例子2、 awk实现实时监控网卡流量脚本(常见应用二)
实现原理:
[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 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
proc/net/dev 文件保存了网卡总流量信息,通过间隔一段间隔,将入网卡与出记录加起来。减去之前就得到实际速率。
程序代码:
awk 'BEGIN{
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);
}
}'
说明:第一个while 是获得总的初始值,$1是网卡出流量,$10是网卡进流量。第2个while会间隔1秒钟启动一次。计算总流量差得到平均每秒流量。
注意:通过getline 逐行读取文件,需要close关闭 。否则在第2次while循环中不能获得数据。
例子3
网卡监控脚步:
一个脚本命令就可以实现监控网卡实时流量情况。
脚本代码内容:
#!/bin/bash
if [ -z "$1" ]; then
echo
echo usage: $0 network-interface
echo
echo e.g. $0 eth0
echo
exit
fi
IF=$1
while true
do
R1=`cat /sys/class/net/$1/statistics/rx_bytes`
T1=`cat /sys/class/net/$1/statistics/tx_bytes`
sleep 1
R2=`cat /sys/class/net/$1/statistics/rx_bytes`
T2=`cat /sys/class/net/$1/statistics/tx_bytes`
TBPS=`expr $T2 - $T1`
RBPS=`expr $R2 - $R1`
TKBPS=`expr $TBPS / 1024`
RKBPS=`expr $RBPS / 1024`
echo "tx $1: $TKBPS kb/s rx $1: $RKBPS kb/s"
done
脚步使用方法:
1.为了使脚本文件可以方便使用,所以放置到/sbin目录下。
#cd /sbin
#vim netspeed
输入脚步内容保存退出。
#chmod +x netspeed
2.使用脚步命令:
#netspeed eth0
(这里是根据主机上网卡信息输入网卡名字,如果不清楚网卡信息,可以使用 ifconfig 命令查看)