[SHELL] LINUX流量監控腳本

最近比較忙,很久沒更新博客了,今天恰好不忙寫了一個流量監控腳本.centos

測試在centos下已經過,有須要的朋友能夠試試,有BUG或者須要添加其餘功能話能夠給我留言.bash


# vi /etc/rc.d/traffic_monitor.shide

----------------------------------------------函數

#!/bin/bash測試

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin;blog

export PATHip


function traffic_monitor {get

  # 系統版本博客

  OS_NAME=$(sed -n '1p' /etc/issue)it


  # 網口名

  eth=$1


  #判斷網卡存在與否,不存在則退出

  if [ ! -d /sys/class/net/$eth ];then

      echo -e "Network-Interface Not Found"

      echo -e "You system have network-interface:\n`ls /sys/class/net`"

      exit 5

  fi


  while [ "1" ]

  do

    # 狀態

    STATUS="fine"


    # 獲取當前時刻網口接收與發送的流量

    RXpre=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $2}')

    TXpre=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $10}')


    # 獲取1秒後網口接收與發送的流量

    sleep 1

    RXnext=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $2}')

    TXnext=$(cat /proc/net/dev | grep $eth | tr : " " | awk '{print $10}')

    clear


    # 獲取這1秒鐘實際的進出流量

    RX=$((${RXnext}-${RXpre}))

    TX=$((${TXnext}-${TXpre}))


    # 判斷接收流量若是大於MB數量級則顯示MB單位,不然顯示KB數量級

    if [[ $RX -lt 1024 ]];then

      RX="${RX}B/s"

    elif [[ $RX -gt 1048576 ]];then

      RX=$(echo $RX | awk '{print $1/1048576 "MB/s"}')

      $STATUS="busy"

    else

      RX=$(echo $RX | awk '{print $1/1024 "KB/s"}')

    fi


    # 判斷髮送流量若是大於MB數量級則顯示MB單位,不然顯示KB數量級

    if [[ $TX -lt 1024 ]];then

      TX="${TX}B/s"

      elif [[ $TX -gt 1048576 ]];then

      TX=$(echo $TX | awk '{print $1/1048576 "MB/s"}')

    else

      TX=$(echo $TX | awk '{print $1/1024 "KB/s"}')

    fi


    # 打印信息

    echo -e "==================================="

    echo -e "Welcome to Traffic_Monitor stage"

    echo -e "version 1.0"

    echo -e "Since 2014.2.26"

    echo -e "Created by showerlee"

    echo -e "BLOG: http://www.showerlee.com"

    echo -e "==================================="

    echo -e "System: $OS_NAME"

    echo -e "Date:   `date +%F`"

    echo -e "Time:   `date +%k:%M:%S`"

    echo -e "Port:   $1"

    echo -e "Status: $STATUS"

    echo -e  " \t     RX \tTX"

    echo "------------------------------"


    # 打印實時流量

    echo -e "$eth \t $RX   $TX "

    echo "------------------------------"

    # 退出信息

    echo -e "Press 'Ctrl+C' to exit"

  done

}

# 判斷執行參數

if [[ -n "$1" ]];then

  # 執行函數

  traffic_monitor $1

else

  echo -e "None parameter,please add system netport after run the script! \nExample: 'sh traffic_monitor eth0'"

fi

----------------------------------------------


# sh traffic_monitor.sh eth0

如圖:

wKioL1MNd02Qn49JAADk0VmZgas201.jpg

相關文章
相關標籤/搜索