eth0)#!/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 &
# /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 確認介面名稱。rx_bytes 可能溢位,建議 64 位系統或定期重啟腳本。docker0、veth* 等也可監控,只要 /sys/class/net/ 下有統計檔即可。利用 /sys/class/net/ 核心暴露的計數器,無需安裝額外工具即可實現輕量級流量監控。配合 systemd 與 logrotate,即可構建生產級的網卡流量審計體系。