shell脚本监控linux网卡流量(上传/下载/流入/流出)
从网上找的一个脚本, diy了一下, 觉得很OK, ~_~
#!/bin/sh
#filename: monitor_eth_flow.v2.sh #功能: 监控网卡进出流量 #用法: # sh monitor_eth_flow.v2.sh # sh monitor_eth_flow.v2.sh eth0 # sh monitor_eth_flow.v2.sh eth0 1 # function calcFlow() { before=$1 after=$2 seconds=$3 title=$4 if [ -z "$before" ]; then before=0 fi if [ -z "$after" ]; then after=0 fi if [ $after -ge $before ] then diffentvalue=$((($after-$before)/$seconds)); else diffentvalue=$((($after+4*1024*1024*1024-$before)/$seconds)); fi diffentvalue=${diffentvalue#-} if [ $diffentvalue -ge 1073741824 ]; then resultend=$(($diffentvalue/1073741824)); unit=GB/s; elif [ $diffentvalue -ge 1048576 ]; then resultend=$(($diffentvalue/1048576)); unit=MB/s; elif [ $diffentvalue -ge 1024 ]; then resultend=$(($diffentvalue/1024)); unit=KB/s; else resultend=$diffentvalue ; unit=B/s; fi echo "$title $resultend$unit" } #监控网卡名, eth0/eth1/lo if [ "-$1" = "-" ] ;then eth="eth0" #默认eth0 else eth=$1 fi #监控时长 if [ "-$2" = "-" ] ;then sleep_seconds=5 #默认5秒 else sleep_seconds=$2 fi echo "网卡 $eth 流量计算中, 请等待$sleep_seconds秒钟......(Ctrl+C停止)"; echo ""; while((1==1)); do resultIn=$(ifconfig $eth | grep -e 'RX bytes'|awk '{print $2}'|awk -F':' '{print $2}'); resultOut=$(ifconfig $eth | grep -e 'RX bytes'|awk '{print $6}'|awk -F':' '{print $2}'); sleep $sleep_seconds; resultIn2=$(ifconfig $eth | grep -e 'RX bytes'|awk '{print $2}'|awk -F':' '{print $2}'); resultOut2=$(ifconfig $eth | grep -e 'RX bytes'|awk '{print $6}'|awk -F':' '{print $2}'); echo $(date +'%Y-%m-%d %H:%M:%S') calcFlow $resultIn $resultIn2 $sleep_seconds "下载流量(进): "; calcFlow $resultOut $resultOut2 $sleep_seconds "上传流量(出):"; echo ""; done