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

Linux 網卡流量監控 Shell 腳本(即時顯示 KB/s)

編輯:Linux 教學

腳本功能

  • 指定網卡(預設 eth0)
  • 採樣間隔可配置(預設 10 秒)
  • 計算平均上傳/下載速率(KB/s)
  • 帶時間戳寫入日誌,支援 logrotate

腳本完整代碼

#!/bin/bash
# net_monitor.sh
# 用法:./net_monitor.sh [介面] [間隔秒數] [日誌目錄]
# 例:./net_monitor.sh eth0 10 /var/log/net_monitor

IFACE=${1:-eth0}
INTERVAL=${2:-10}
LOG_DIR=${3:-/var/log/net_monitor}
LOG_FILE="$LOG_DIR/net_$(date +%Y%m%d).log"

mkdir -p "$LOG_DIR"

# 讀取 /sys/class/net//statistics/{rx,tx}_bytes
read_rx_tx() {
    local rx tx
    rx=$(cat "/sys/class/net/$IFACE/statistics/rx_bytes" 2>/dev/null) || { echo "介面 $IFACE 不存在"; exit 1; }
    tx=$(cat "/sys/class/net/$IFACE/statistics/tx_bytes" 2>/dev/null)
    echo "$rx $tx"
}

echo "開始監控 $IFACE,間隔 ${INTERVAL}s,日誌:$LOG_FILE"
echo "按 Ctrl+C 停止"

while true; do
    read r1 t1 <<<$(read_rx_tx)
    sleep "$INTERVAL"
    read r2 t2 <<<$(read_rx_tx)

    # 計算 KB/s(bytes 差值 / 1024 / 間隔秒數)
    rx_kbps=$(( (r2 - r1) / 1024 / INTERVAL ))
    tx_kbps=$(( (t2 - t1) / 1024 / INTERVAL ))

    timestamp=$(date '+%Y%m%d %H:%M:%S')
    echo "下載: ${rx_kbps} KB/s  上傳: ${tx_kbps} KB/s  $timestamp" >> "$LOG_FILE"
    echo "下載: ${rx_kbps} KB/s  上傳: ${tx_kbps} KB/s  $timestamp"
done

使用範例

chmod +x net_monitor.sh

# 前台運行(測試)
./net_monitor.sh eth0 10 /tmp/netlog

# 後台常駐(生產建議用 systemd 服務)
nohup ./net_monitor.sh eth0 10 /var/log/net_monitor >/dev/null 2>&1 &

systemd 服務單元範例

# /etc/systemd/system/net-monitor@.service
[Unit]
Description=Network Traffic Monitor for %i
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/sbin/net_monitor.sh %i 10 /var/log/net_monitor
Restart=on-failure
User=root

[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable net-monitor@eth0
systemctl start net-monitor@eth0

日誌輪轉配置

# /etc/logrotate.d/net_monitor
/var/log/net_monitor/net_*.log {
    daily
    rotate 30
    compress
    missingok
    notifempty
    create 640 root root
    sharedscripts
    postrotate
        systemctl reload net-monitor@eth0 >/dev/null 2>&1 || true
    endscript
}

進階:多網卡同時監控

for iface in eth0 eth1; do
    systemctl enable net-monitor@$iface
    systemctl start net-monitor@$iface
done

常見問題

  • 介面不存在:腳本會自動退出並報錯,請用 ip link 確認介面名稱。
  • 計算溢位:32 位系統長時間運行 rx_bytes 可能溢位,建議 64 位系統或定期重啟腳本。
  • 虛擬介面:docker0、veth* 等也可監控,只要 /sys/class/net/ 下有統計檔即可。

總結

利用 /sys/class/net/ 核心暴露的計數器,無需安裝額外工具即可實現輕量級流量監控。配合 systemd 與 logrotate,即可構建生產級的網卡流量審計體系。

Copyright © Windows教程網 All Rights Reserved