# vi/etc/rc.d/traffic_monitor.sh
----------------------------------------------
#!/bin/Bashpath=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/Sbin;export PATHfunctionTraffic_monitor {# system version Os_name=$(sed-N'1p'/etc/issue) # Network port name ETH=$1#判断网卡存在与否, exit if not presentif[!-d/sys/class/net/$eth]; Then Echo-E"Network-interface not Found" Echo-E"You system has network-interface:\n ' ls/sys/class/net '"Exit5 fi while["1" ] Do# state Status="Fine"# Gets the current time the network port receives and sends the traffic Rxpre=$(Cat/proc/net/dev |grep$eth |TR:" "|awk '{print $}') Txpre=$(Cat/proc/net/dev |grep$eth |TR:" "|awk '{print $}'# gets 1 seconds after the network port receives and sends trafficSleep 1Rxnext=$(Cat/proc/net/dev |grep$eth |TR:" "|awk '{print $}') Txnext=$(Cat/proc/net/dev |grep$eth |TR:" "|awk '{print $}') Clear# Get this 1 seconds actual incoming and outgoing RX=$ ((${rxnext}-${rxpre})) TX=$ ((${txnext}-${txpre})) # to determine if the received traffic is larger than the MB level, the MB units are displayed, otherwise the KB order of magnitudeif[[$RX-lt1024x768]]; ThenRX="${rx}b/s" elif[[$RX-GT1048576]]; ThenRX=$(Echo$RX |awk '{print $1/1048576 "MB/S"}') $STATUS="Busy" ElseRX=$(Echo$RX |awk '{print $1/1024 "kb/s"}') fi# To determine if the sending traffic is larger than the MB level, the MB units are displayed, otherwise the KB order of magnitudeif[[$TX-lt1024x768]]; ThenTX="${tx}b/s" elif[[$TX-GT1048576]]; ThenTX=$(Echo$TX |awk '{print $1/1048576 "MB/S"}') ElseTX=$(Echo$TX |awk '{print $1/1024 "kb/s"}') fi# Print InformationEcho-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: $" Echo-E"Status: $STATUS" Echo-E"\ t RX \ttx" Echo "------------------------------"# Print Live trafficEcho-E"$eth \ t $RX $TX" Echo "------------------------------"# Exit InformationEcho-E"Press ' CTRL + C ' to exit" Done}# Judging execution Parametersif[[-N" $"]]; Then# Execute function traffic_monitor $1Else Echo-E"None parameter,please Add system Netport after run the script! \nexample: ' sh traffic_monitor eth0 '"fi
----------------------------------------------
Ii. Effect of implementation
Copy CodeThe code is as follows: # sh traffic_monitor.sh eth0
Monitor traffic shell scripts