今天碰到一个问题:如何用Shell实现实时监控网卡流量?
不清楚,于是搜索:{http://cn.bing.com/search?q=linux+real+time+network+speed+shell}
# 1.通过ifconfig命令
#!/bin/bash while : ; do time=`date +%Y"-"%m"-"%d" "%k":"%M` nic=`ifconfig |grep eth|awk '{print $1}'` rx_before=`ifconfig $nic|sed -n "8"p|awk '{print $2}'|cut -c7-` tx_before=`ifconfig $nic|sed -n "8"p|awk '{print $6}'|cut -c7-` sleep 2 rx_after=`ifconfig $nic|sed -n "8"p|awk '{print $2}'|cut -c7-` tx_after=`ifconfig $nic|sed -n "8"p|awk '{print $6}'|cut -c7-` rx_result=$[(rx_after-rx_before)/256] tx_result=$[(tx_after-tx_before)/256] echo "$time In_Speed: "$rx_result"kbps Out_Speed: "$tx_result"kbps" sleep 2 done
# 2.通过读取”/proc/net/dev”文件
awk 'BEGIN{ OFMT="%.3f"; devf="/proc/net/dev"; while(("cat "devf) | getline) { if($0 ~ /:/ && ($10+0) > 0) { split($1,tarr,":"); net[tarr[1]]=$10+tarr[2]; print tarr[1],$10+tarr[2]; } } close(devf); while((system("sleep 1 ")) >=0) { system("clear"); while( getline < devf ) { if($0 ~ /:/ && ($10+0) > 0) { split($1,tarr,":"); if(tarr[1] in net) { print tarr[1],":",($10+tarr[2]-net[tarr[1]])*8/1024,"kb/s"; net[tarr[1]]=$10+tarr[2]; } } } close(devf); } }'
# 3.通过读取”/sys/class/net/eth0/statistics/rx_bytes”等文件内容{在/sys/class/net/eth0/statistics/目录下还有更多的统计信息}
#!/bin/bash if [ -z "$1" ]; then echo echo Usage: ./$0 network-interface echo echo Example: ./$0 eth0 echo exit fi IF=$1 while true do R1=`cat /sys/class/net/$1/statistics/rx_bytes` T1=`cat /sys/class/net/$1/statistics/tx_bytes` sleep 1 R2=`cat /sys/class/net/$1/statistics/rx_bytes` T2=`cat /sys/class/net/$1/statistics/tx_bytes` TBPS=`expr $T2 - $T1` RBPS=`expr $R2 - $R1` TKBPS=`expr $TBPS / 1024` RKBPS=`expr $RBPS / 1024` echo "tx $1: $TKBPS kb/snrx $1: $RKBPS kb/s" done
# 4.通过第三方工具”nload/ifstat/iftop”
参考网址:
- shell awk实现实时监控网卡流量脚本(常见应用二) – 程默
- Linux: Check Network Connection Command
- http://www.cyberciti.biz/networking/nload-linux-command-to-monitor-network-traffic-bandwidth-usage/
- http://www.apinglai.com/linux-%e7%9b%91%e6%8e%a7%e7%bd%91%e5%8d%a1%e5%ae%9e%e6%97%b6%e6%b5%81%e9%87%8f%e5%b8%a6%e5%ae%bd-%e8%84%9a%e6%9c%ac/
- Linux网络流量实时监控ifstat iftop命令详解 – ggjucheng
《 “Linux Shell实时监控网卡流量” 》 有 3 条评论
Stacer – Linux 系统优化与监控工具
https://github.com/oguzhaninan/Stacer
[译] Linux网络栈监控和调优:接收数据
https://arthurchiao.github.io/blog/tuning-stack-rx-zh-5/
…
https://arthurchiao.github.io/blog/tuning-stack-rx-zh-1/
Mercury – 思科开源了一个用于分析和捕获网络流量的 Linux 工具 (Mercury: network fingerprinting and packet metadata capture)
https://github.com/cisco/mercury