雖然 Cacti、Zabbix、Prometheus 等監控平台功能強大,但針對特定指標的輕量級 Shell 腳本往往更靈活、部署門檻更低。本文提供 5 個可直接落地的 Bash 腳本,涵蓋網卡即時流量、系統資源快照、磁碟空間閾值告警、CPU/記憶體 CSV 長期記錄、定時全項效能採集,滿足從臨時排查到持續基線記錄的多樣需求。
#!/bin/bash
# net_speed.sh - 每 2 秒顯示 eth0 進/出速率 (kbps)
while true; do
time=$(date +"%m-%d %H:%M")
rx_before=$(cat /proc/net/dev | awk '/eth0:/ {print $2}')
tx_before=$(cat /proc/net/dev | awk '/eth0:/ {print $10}')
sleep 2
rx_after=$(cat /proc/net/dev | awk '/eth0:/ {print $2}')
tx_after=$(cat /proc/net/dev | awk '/eth0:/ {print $10}')
rx_kbps=$(( (rx_after - rx_before) / 2048 ))
tx_kbps=$(( (tx_after - tx_before) / 2048 ))
echo "$time In: ${rx_kbps} kbps Out: ${tx_kbps} kbps"
done
改進點:改用 /proc/net/dev 避免 ifconfig 輸出格式差異;單位換算為 kbps(除 1024 再除取樣秒數)。
#!/bin/bash
# sys_snapshot.sh - 記錄 CPU、記憶體、磁碟、連線數至 /tmp
IP="192.168.1.227"
top -bn2 | grep "Cpu" | tail -1 > /tmp/cpu.txt
free -m | grep Mem > /tmp/mem.txt
df -h | grep -E "sda1|/mnt/storage" > /tmp/disk.txt
time=$(date +"%m.%d %H:%M")
conn=$(netstat -na | grep "$IP:80" | wc -l)
echo "$time $conn" >> /tmp/conn_count.txt
可加入 crontab 每分鐘執行,配合 logrotate 管理檔案大小。
#!/bin/bash
# disk_alert.sh - 根分區使用率 ≥90% 發送郵件
SPACE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$SPACE" -ge 90 ]; then
echo "磁碟使用率 ${SPACE}% 超過閾值" | mail -s "磁碟告警 $(hostname)" admin@example.com
fi
需確保 mail 指令可用(安裝 mailutils/postfix)。
#!/bin/bash
# capstats.sh - 每次執行追加一行 CSV
OUTFILE="/home/xu/capstats.csv"
DATE=$(date +"%m/%d/%Y")
TIME=$(date +"%H:%M:%S")
UPTIME=$(uptime)
VMOUT=$(vmstat 1 2 | tail -1)
USERS=$(echo $UPTIME | awk '{print $4}')
LOAD=$(echo $UPTIME | awk '{print $10}' | sed 's/,//')
FREE=$(echo $VMOUT | awk '{print $4}')
IDLE=$(echo $VMOUT | awk '{print $15}')
echo "$DATE,$TIME,$USERS,$LOAD,$FREE,$IDLE" >> $OUTFILE
匯入 Excel/Google Sheets 即可繪製趨勢圖。
#!/bin/bash
# check_all.sh - 每小時在 /home/oslog/host_YYYYMMDD/HH 建立完整效能日誌
DAT=$(date +"%Y%m%d")
HOUR=$(date +"%H")
DIR="/home/oslog/host_${DAT}/${HOUR}"
DELAY=60
COUNT=60
mkdir -p "$DIR"
export TERM=linux
top -b -d $DELAY -n $COUNT > "$DIR/top_${DAT}.log" 2>&1 &
sar -u $DELAY $COUNT > "$DIR/cpu_${DAT}.log" 2>&1 &
vmstat $DELAY $COUNT > "$DIR/vmstat_${DAT}.log" 2>&1 &
iostat $DELAY $COUNT > "$DIR/iostat_${DAT}.log" 2>&1 &
sar -n DEV $DELAY $COUNT > "$DIR/net_${DAT}.log" 2>&1 &
wait
chmod +x check_all.sh
echo "0 * * * * root /home/check_all.sh" >> /etc/crontab
/home/oslog/
└── host_20240520/
├── 00/
│ ├── top_20240520.log
│ ├── cpu_20240520.log
│ ├── vmstat_20240520.log
│ ├── iostat_20240520.log
│ └── net_20240520.log
└── 01/ ...
出現效能問題時,直接查看對應小時目錄下的各項日誌,快速定位瓶頸。
#!/bin/bash 並 chmod +x。