统计网卡TX(发送)RX(接受)流量脚本

显示网卡流量的方法蛮多,一般我们可以通过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

 

原文地址:https://www.cnblogs.com/flish/p/5799949.html