使用shell脚本计算Linux网卡流量,方法中最关键点:
复制代码 代码如下:
ifconfig $eth_name | grep bytes | awk '{print $6}' | awk -F : '{print $2}'
通过ifconfig eth0|grep bytes 得到输入输出的流量。
复制代码 代码如下:
/@rac2=>dd2$ifconfig eth0|grep bytes
RX bytes:1638005313300 (1.4 TiB) TX bytes:3408060482049 (3.0 TiB)
再将结果通过awk 得出所要的字段值。
固定时间得到这些值,在写个循环计算一下就能得到网卡流量。
完整代码:
代码一:
#!/bin/bash# 统计网卡流量# link: ### while : do Time=`date +%F” “%T.%N` rx_before=`ifconfig eth0 |sed -n 8p |awk ‘{print $2}'| cut -c7-` tx_before=`ifconfig eth0 |sed -n 8p |awk ‘{print $6}'| cut -c7-` sleep 2 rx_after=`ifconfig eth0 |sed -n 8p |awk ‘{print $2}'| cut -c7-` tx_after=`ifconfig eth0 |sed -n 8p |awk ‘{print $6}'| cut -c7-` rx_result=$[(rx_after – rx_before)/512] tx_result=$[(tx_after – tx_before)/512] echo -e “$Time nNow_In_Speed: ‘$rx_result'Kbps Now_OUt_Speed: ‘$tx_result'Kbpsn” done