顯示網卡流量的方法蠻多,一般我們可以通過dstat來查看,但dstat不一定所有的機器都有安裝。而我們知道,通過ifconfig可以看到某一網卡發送與接收的字節數,所以我們可以寫一個腳本來統計一下。
先看ifconfig:
# ifconfig eth0
eth0 Link encap:Ethernet HWaddr 82:EC:7A:2B:7D:28
inet addr:173.231.43.132 Bcast:173.231.43.143 Mask:255.255.255.240
inet6 addr: fe80::80ec:7aff:fe2b:7d28/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:5726191 errors:0 dropped:0 overruns:0 frame:0
TX packets:2883102 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:676588247 (645.2 MiB) TX bytes:1438457672 (1.3 GiB)
我們可以看到RX(接受)與TX(發送)兩個數據,於是我們的腳本出來了:
#!/bin/bash
if [ ! -n "$1" ] ;then
echo "must input Ethernet port!"
exit 0
else
echo "input $1"
fi
alias ifconfig="/sbin/ifconfig"
eth=$1
while true; do
RXpre=$(ifconfig ${eth} | grep bytes | awk '{print $2}'| awk -F":" '{print $2}')
TXpre=$(ifconfig ${eth} | grep bytes | awk '{print $6}' | awk -F":" '{print $2}')
sleep 1
RXnext=$(ifconfig ${eth} | grep bytes | awk '{print $2}'| awk -F":" '{print $2}')
TXnext=$(ifconfig ${eth} | grep bytes | awk '{print $6}' | awk -F":" '{print $2}')
echo RX ----- TX
echo "$((((${RXnext}-${RXpre})/1024)/1024*8))Mb/s $((((${TXnext}-${TXpre})/1024/1024*8)))Mb/s"
done
腳本比較簡單,可以添加一些參數判斷,比如多長時間顯示一次等等,先看看執行結果:
RX ----- TX
5MB/s 7MB/s
RX ----- TX
5MB/s 7MB/s
RX ----- TX
4MB/s 6MB/s
RX ----- TX
4MB/s 6MB/s
RX ----- TX
