- 相關(guān)推薦
Linux使用shell腳本監(jiān)控高速網(wǎng)絡(luò)流量的方法
在Linux系統(tǒng)操作中,可使用工具監(jiān)控網(wǎng)絡(luò)流量,但對(duì)高速網(wǎng)絡(luò)的監(jiān)控有一定的局限性,對(duì)于高速網(wǎng)絡(luò)流量的監(jiān)控可使用shell腳本,下面小編就給大家介紹下Linux使用shell腳本監(jiān)控高速網(wǎng)絡(luò)流量的方法。
在本文中我們介紹一種簡(jiǎn)單的Shell 腳本,它可以監(jiān)控網(wǎng)絡(luò)流量而且不依賴(lài)于緩慢的libpcap庫(kù)。這些腳本支持Gb以上規(guī)模的高速網(wǎng)絡(luò)接口,如果你對(duì)“匯聚型”的網(wǎng)絡(luò)流量感興趣的話,它們可統(tǒng)計(jì)每個(gè)網(wǎng)絡(luò)接口上的流量。
腳本主要是基于sysfs虛擬文件系統(tǒng),這是由內(nèi)核用來(lái)將設(shè)備或驅(qū)動(dòng)相關(guān)的信息輸出到用戶空間的一種機(jī)制。網(wǎng)絡(luò)接口的相關(guān)分析數(shù)據(jù)會(huì)通過(guò)“/sys/class/net/《ethX》/statistics”輸出。
舉個(gè)例子,eth0的網(wǎng)口上分析報(bào)告會(huì)輸出到這些文件中:
/sys/class/net/eth0/statistics/rx_packets: 收到的數(shù)據(jù)包數(shù)據(jù)
/sys/class/net/eth0/statistics/tx_packets: 傳輸?shù)臄?shù)據(jù)包數(shù)量
/sys/class/net/eth0/statistics/rx_bytes: 接收的字節(jié)數(shù)
/sys/class/net/eth0/statistics/tx_bytes: 傳輸?shù)淖止?jié)數(shù)
/sys/class/net/eth0/statistics/rx_dropped: 當(dāng)收到包數(shù)據(jù)包下降的數(shù)據(jù)量
/sys/class/net/eth0/statistics/tx_dropped: 傳輸包數(shù)據(jù)包下降的數(shù)據(jù)量
這些數(shù)據(jù)會(huì)根據(jù)內(nèi)核數(shù)據(jù)發(fā)生變更的時(shí)候自動(dòng)刷新。因此,你可以編寫(xiě)一系列的腳本進(jìn)行分析并計(jì)算流量統(tǒng)計(jì)。下面就是這樣的腳本(感謝 joemiller 提供)。第一個(gè)腳本是統(tǒng)計(jì)每秒數(shù)據(jù)量,包含接收(RX)或發(fā)送(TX)。而后面的則是一個(gè)描述網(wǎng)絡(luò)傳輸中的接收(RX)發(fā)送(TX)帶寬。這些腳本中安裝不需要任何的工具。
測(cè)量網(wǎng)口每秒數(shù)據(jù)包:
#!/bin/bash
INTERVAL=“1” # interval in seconds
if [ -z “$1” ]; then
echo
echo usage: $0 [network-interface]
echo
echo e.g. $0 eth0
echo
echo shows packets-per-second
exit
fi
IF=$1
while true
do
R1=`cat /sys/class/net/$1/statistics/rx_packets`
T1=`cat /sys/class/net/$1/statistics/tx_packets`
sleep $INTERVAL
R2=`cat /sys/class/net/$1/statistics/rx_packets`
T2=`cat /sys/class/net/$1/statistics/tx_packets`
TXPPS=`expr $T2 - $T1`
RXPPS=`expr $R2 - $R1`
echo “TX $1: $TXPPS pkts/s RX $1: $RXPPS pkts/s”
done
網(wǎng)絡(luò)帶寬測(cè)量
#!/bin/bash
INTERVAL=“1” # interval in seconds
if [ -z “$1” ]; then
echo
echo usage: $0 [network-interface]
echo
echo e.g. $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 $INTERVAL
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/s RX $1: $RKBPS kb/s”
done
下面的屏幕截圖顯示了上面的兩個(gè)腳本的輸出。
上面就是Linux使用shell腳本監(jiān)控高速網(wǎng)絡(luò)流量的方法介紹了,使用這些腳本能夠統(tǒng)計(jì)出每個(gè)網(wǎng)絡(luò)接口的流量,將其生成監(jiān)控報(bào)告。
【Linux使用shell腳本監(jiān)控高速網(wǎng)絡(luò)流量的方法】相關(guān)文章:
Linux Shell腳本教程(一):Shell入門(mén)09-01
Linux Shell腳本系列教程詳細(xì)介紹08-05
PHP腳本修改Linux系統(tǒng)口令的方法09-05
PHP腳本修改Linux或Unix系統(tǒng)口令方法10-18
關(guān)于linux使用方法09-20
安裝和使用Linux CURL的方法10-23
Linux的free命令使用方法09-10