萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 部署 MRTG 監控網路流量、CPU、記憶體與磁碟完整實戰

簡介

MRTG (Multi Router Traffic Grapher) 透過 SNMP 協定讀取設備計數器,生成 PNG 圖表嵌入 HTML,直觀展示流量、負載、記憶體、磁碟等指標趨勢。

1. 安裝 SNMP 服務

yum -y install net-snmp net-snmp-utils
# 配置 /etc/snmp/snmpd.conf
rocommunity public
disk / 13102744
disk /data 41279536
systemctl enable --now snmpd

2. 安裝 MRTG

yum -y install mrtg

3. 產生配置檔範本

使用 cfgmaker 自動生成,再手動微調:

cfgmaker --global 'WorkDir: /var/www/mrtg' \
         --global 'Options[_]: growright,bits' \
         --output /etc/mrtg/mrtg.cfg \
         public@localhost

4. 關鍵監控項配置範例

網卡流量 (eth0)

Target[eth0]: \eth0:public@localhost
MaxBytes[eth0]: 12500000
Title[eth0]: eth0 流量統計
PageTop[eth0]: 

eth0 網卡流量

Options[eth0]: growright,nopercent YLegend[eth0]: Bytes/s ShortLegend[eth0]: B/s LegendI[eth0]: 入站 LegendO[eth0]: 出站

CPU 負載

Target[cpuload]: .1.3.6.1.4.1.2021.11.50.0&.1.3.6.1.4.1.2021.11.53.0:public@localhost
MaxBytes[cpuload]: 100
Options[cpuload]: gauge,nopercent,growright
YLegend[cpuload]: CPU %
ShortLegend[cpuload]: %
LegendI[cpuload]: User
LegendO[cpuload]: Idle
Title[cpuload]: CPU 使用率

記憶體使用

Target[mem]: .1.3.6.1.4.1.2021.4.6.0&.1.3.6.1.4.1.2021.4.4.0:public@localhost
MaxBytes1[mem]: 1048576
MaxBytes2[mem]: 2097152
Options[mem]: gauge,growright
YLegend[mem]: Bytes
Title[mem]: 記憶體與 Swap 使用量

磁碟使用率

Target[disk]: .1.3.6.1.4.1.2021.9.1.8.1&.1.3.6.1.4.1.2021.9.1.8.2:public@localhost
MaxBytes1[disk]: 13102744
MaxBytes2[disk]: 41279536
Options[disk]: gauge,growright
Title[disk]: 磁碟空間使用率

5. 定時執行與首次生成索引

# /etc/cron.d/mrtg 已自動建立,預設 5 分鐘執行一次
# 首次需手動跑 3 次消除初始化錯誤
LANG=C LC_ALL=C /usr/bin/mrtg /etc/mrtg/mrtg.cfg --lock-file /var/lock/mrtg/mrtg_l --confcache-file /var/lib/mrtg/mrtg.ok
# 生成首頁
indexmaker --output=/var/www/mrtg/index.html --title="伺服器監控儀表板" /etc/mrtg/mrtg.cfg

6. 進階技巧

  • HTTPS:配置 Apache/Nginx 反向代理 MRTG 目錄並啟用 TLS。
  • 多伺服器聚合:在中央節點用 cfgmaker 指定多個 public@host。
  • 自定義 OID:透過 snmpwalk 發現廠商私有 OID,擴充監控項(如 RAID 狀態、溫度)。

7. 故障排查

  • 圖表不更新 → 檢查 cron 日誌、/var/lib/mrtg/*.log 權限、SNMP 連通性(snmpwalk -v2c -c public localhost)。
  • 數值異常 → 確認 MaxBytes 設定是否符合實際介面速率(位元組 vs 位元)。
copyright © 萬盛學電腦網 all rights reserved