cszer

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

分类: 技术, shell       评论: 1   阅读:1,815 views

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
#!/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 "%s \t %30s \t %30s \t %30s\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"

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

除非注明,文章皆由( csz )原创,转载请标明本文地址
本文地址: http://www.cszhi.com/20121030/displays-the-current-traffic-by-shell.html

10-30
2012

发表评论