#!/bin/bash #作者:fafu_li #时间:2015.10.14 #监控网卡传输速率 source /etc/profile #加载系统环境变量 source $HOME/.bash_profile #加载用户环境变量 set -o nounset #引用未初始化变量时终止执行,也可以set -u #set -o errexit #执行任何语句返回非0状态时终止执行,也可以set -e #定义监控的网卡 INET=("eth0" "lo") net_monitor() { interface=$1 ifconfig $interface > /dev/null 2>&1 if [[ $? != 0 ]];then echo "$interface 不存在" else RX1=$(cat /proc/net/dev | grep $interface | awk -F ":" '{print $2}' | awk -F " " '{print $1}') TX1=$(cat /proc/net/dev | grep $interface | awk -F ":" '{print $2}' | awk -F " " '{print $9}') sleep 1 RX2=$(cat /proc/net/dev | grep $interface | awk -F ":" '{print $2}' | awk -F " " '{print $1}') TX2=$(cat /proc/net/dev | grep $interface | awk -F ":" '{print $2}' | awk -F " " '{print $9}') let total_RX=$RX2-$RX1 let total_TX=$TX2-$TX1 if [ $total_RX -lt 1024 ];then total_RX="${total_RX} B/s" elif [ $total_RX -gt 1048576 ];then total_RX=$(echo $total_RX | awk '{printf "%.2f",$1/1048576}')" MB/s" else total_RX=$(echo $total_RX | awk '{printf "%.2f",$1/1024}')" KB/S" fi if [ $total_TX -lt 1024 ];then total_TX="${total_TX} B/s" elif [ $total_TX -gt 1048576 ];then total_TX=$(echo $total_TX | awk '{printf "%.2f",$1/1048576}')" MB/s" else total_TX=$(echo $total_TX | awk '{printf "%.2f", $1/1024}')" KB/S" fi echo "$interface 接收: $total_RX 发送: $total_TX" fi } while true;do echo "---------------------------------------------------------------" for i in ${INET[@]};do net_monitor $i done done