Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Shell 實時監控網卡流量腳本(基於 /proc/net/dev)

編輯:Linux 教學

改進版腳本(修正原碼語法錯誤、支援多網卡、單位自適應)

#!/bin/bash
# net_monitor.sh - 實時顯示網卡進出流量速率
# 用法: ./net_monitor.sh [interface] [interval_seconds]
# 例: ./net_monitor.sh eth0 2

IFACE="${1:-eth0}"
INTERVAL="${2:-2}"

# 讀取 /proc/net/dev 獲取計數器(不依賴 ifconfig/ip,效能更高)
read_counters() {
    awk -v iface="$IFACE" '$1 ~ iface":" {print $2, $10}' /proc/net/dev
}

# 單位自適應格式化
fmt() {
    local b=$1
    if (( b > 1073741824 )); then
        printf "%.2f GB/s" "$(echo "scale=2; $b/1073741824" | bc)"
    elif (( b > 1048576 )); then
        printf "%.2f MB/s" "$(echo "scale=2; $b/1048576" | bc)"
    elif (( b > 1024 )); then
        printf "%.2f KB/s" "$(echo "scale=2; $b/1024" | bc)"
    else
        printf "%d B/s" "$b"
    fi
}

echo "Monitoring $IFACE every ${INTERVAL}s ... (Ctrl+C to stop)"
printf "%-20s %-15s %-15s\n" "TIME" "RX SPEED" "TX SPEED"

read rx1 tx1 < <(read_counters)
while true; do
    sleep "$INTERVAL"
    read rx2 tx2 < <(read_counters)
    rx_rate=$(( (rx2 - rx1) / INTERVAL ))
    tx_rate=$(( (tx2 - tx1) / INTERVAL ))
    time_str=$(date '+%Y-%m-%d %H:%M:%S')
    printf "%-20s %-15s %-15s\n" "$time_str" "$(fmt $rx_rate)" "$(fmt $tx_rate)"
    rx1=$rx2; tx1=$tx2
done

核心改進點

進階版:多網卡同時監控 + CSV 輸出

#!/bin/bash
# multi_net_monitor.sh
INTERVAL="${1:-2}"
IFACES=($(ls /sys/class/net | grep -vE '^lo$|^docker|^veth|^br-'))
declare -A rx tx

for iface in "${IFACES[@]}"; do
    read rx[$iface] tx[$iface] < <(awk -v i="$iface" '$1~i":"{print $2,$10}' /proc/net/dev)
done

echo "TIME,$(IFS=,; echo "${IFACES[*]/%/_RX},${IFACES[*]/%/_TX}")"
while true; do
    sleep "$INTERVAL"
    line=$(date '+%Y-%m-%d %H:%M:%S')
    for iface in "${IFACES[@]}"; do
        read r t < <(awk -v i="$iface" '$1~i":"{print $2,$10}' /proc/net/dev)
        rx_rate=$(( (r - rx[$iface]) / INTERVAL ))
        tx_rate=$(( (t - tx[$iface]) / INTERVAL ))
        rx[$iface]=$r; tx[$iface]=$t
        line+=",$rx_rate,$tx_rate"
    done
    echo "$line"
done

輸出可直接導入 Excel/時序資料庫(InfluxDB/Prometheus Pushgateway)做長期趨勢分析。

生產級替代方案

  • Prometheus Node Exporter:標準化 node_network_receive_bytes_total/node_network_transmit_bytes_total,配合 Grafana 儀表板。
  • collectd + network plugin:輕量級代理,支援 100+ 指標。
  • Telegraf:InfluxData 出品,插件豐富,輸出直達 InfluxDB/Kafka/HTTP。
  • bcc/BPF 工具:tcplife、tcprtt、netstat 等內核級可觀測工具。

總結

基於 /proc/net/dev 的 Shell 腳本適合臨時排查、無代理環境、嵌入式設備。長期監控請採用標準化時序採集棧(Node Exporter + Prometheus + Grafana),實現告警、關聯分析、容量規劃全鏈路覆蓋。

Copyright © Windows教程網 All Rights Reserved
原碼問題改進方案
反引號 ` 嵌套與引號混亂使用 $() 現代命令替換,結構清晰
依賴 ifconfig 解析第 8 行(不穩定)直接讀 /proc/net/dev,內核計數器,無解析風險
硬編碼單位 KBps,無自適應fmt() 函數自動切換 B/KB/MB/GB
無參數化,僅支援 eth0支援任意介面名與間隔秒數
無退出處理trap 可選,Ctrl+C 自然退出