当前位置: > shell编程 >

脚本实现实时显示linux网络流量

时间:2015-05-11 03:51来源:linux.it.net.cn 作者:IT

vim flow.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/bash
#caishzh 20121030
#displays the current Traffic
 
ETH=$1
ETH=${ETH:-eth0}
IP=`ifconfig $ETH|awk -F '[ :]+' '/inet addr/{print $4}'`
 
while true;do
        let I+=1
        NOW=`date +"%F %T"`
        TX1=`grep $ETH /proc/net/dev | tr : " " | awk '{print $10}'`
        RX1=`grep $ETH /proc/net/dev | tr : " " | awk '{print $2}'`
        sleep 1
        TX2=`grep $ETH /proc/net/dev | tr : " " | awk '{print $10}'`
        RX2=`grep $ETH /proc/net/dev | tr : " " | awk '{print $2}'`
 
        let TX=(TX2-TX1)/1024
        let RX=(RX2-RX1)/1024
        let TX_TOTAL+=$TX
        let RX_TOTAL+=$RX
        let TX_AVERAGE=TX_TOTAL/${I}
        let RX_AVERAGE=RX_TOTAL/${I}
 
        clear
 
        printf "%10s\t%20s\n" "Device $ETH [$IP]" "$NOW"
        echo "============================================================="
        printf "%10s\t%20s\t%20s\n" CURRENT: in:${RX}KB/s out:${TX}KB/s
        printf "%10s\t%20s\t%20s\n" AVERAGE: in:${RX_AVERAGE}KB/s out:${TX_AVERAGE}KB/s
        printf "%10s\t%20s\t%20s\n" TOTAL: in:${RX_TOTAL}KB out:${TX_TOTAL}KB
done

脚本默认显示eth0的流量,如果要显示其它网卡的流量,请在脚本后接网卡名,如:
./flow.sh eth1

运行结果:
flow.sh

另一个版本,就是改了下显示的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/bin/bash
#caishzh 20130311 version 2
#displays the current Traffic
 
LANG=C
ETH=$1
ETH=${ETH:-eth0}
IP=`ifconfig $ETH|awk -F '[ :]+' '/inet addr/{print $4}'`
 
while true;do
        let I+=1
        NOW=`date +"%F %T"`
        TX1=`grep $ETH /proc/net/dev | tr : " " | awk '{print $10}'`
        RX1=`grep $ETH /proc/net/dev | tr : " " | awk '{print $2}'`
        sleep 1
        TX2=`grep $ETH /proc/net/dev | tr : " " | awk '{print $10}'`
        RX2=`grep $ETH /proc/net/dev | tr : " " | awk '{print $2}'`
 
        let TX=(TX2-TX1)/1024
        let RX=(RX2-RX1)/1024
        let TX_TOTAL+=$TX
        let RX_TOTAL+=$RX
        let TX_AVERAGE=TX_TOTAL/${I}
        let RX_AVERAGE=RX_TOTAL/${I}
 
        printf "%10s  %10s  %10s  %10s\t%10s  %10s  %10s\t%10s  %10s  %10s\n" "$NOW" CURRENT: in:${RX}KB/s out:${TX}KB/s AVERAGE: in:${RX_AVERAGE}KB/s out:${TX_AVERAGE}KB/s TOTAL: in:${RX_TOTAL}KB out:${TX_TOTAL}KB
 
done

注:printf那一句是一行,语句太长,自动换行了。



(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容