用MRTG監(jiān)測Linux-CPU監(jiān)控
用MRTG監(jiān)測Linux系統(tǒng)網(wǎng)絡(luò)、CPU、內(nèi)存和硬盤情況
本文講述的是:用MRTG監(jiān)測Linux系統(tǒng)網(wǎng)絡(luò)、CPU、內(nèi)存和硬盤情況:
原理介紹、MRTG安裝監(jiān)控、CPU監(jiān)控、內(nèi)存監(jiān)控、硬盤監(jiān)控
3、獲得我們需要的關(guān)于CPU 和Memory 的數(shù)據(jù)
1), 獲得CPU 的使用率和CPU 的閑置率
為了獲得CPU 的這兩個(gè)數(shù)據(jù),我們使用sar –u 1 3 這個(gè)命令,
- [root@intel zwz]# sar -u 1 3
- Linux 2.4.20-8 (intel) 08/30/2005
- 05:46:16 PM CPU %user %nice %system %idle
- 05:46:17 PM all 0.00 0.00 1.00 99.00
- 05:46:18 PM all 0.00 0.00 0.00 100.00
- 05:46:19 PM all 0.00 0.00 0.00 100.00
- Average: all 0.00 0.00 0.33 99.67
sar 命令執(zhí)行后生成如上圖所示的數(shù)據(jù)。我們需要的是三個(gè)帶下劃線的數(shù)據(jù)。其中:
CPU 的使用率為:%user + %system = 0.00 + 0.33 = 0.33
CPU 的閑置率為:%idle = 99.67
好了只有sar 是不行的,因?yàn)閙rtg 不能識別這些數(shù)據(jù),mrtg 能識別兩個(gè)數(shù)據(jù),所以我們要把0.33 和99.67 傳給mrtg,這很容易實(shí)現(xiàn),我用perl 寫了一個(gè)腳本(cpu.pl)來獲得并輸出這兩個(gè)數(shù)據(jù):腳本如下
- #!/usr/bin/perl
- system ("/usr/bin/sar -u 1 3|grep Average >cpu_info_file"); #sar 輸出寫入文件cpu_info_file
- open (CPUINFO,"cpu_info_file"); #打開cpu_info_file 文件
- @cpuinfo=; # 讀去文件內(nèi)容
- close (CPUINFO); #關(guān)閉文件
- foreach $line(@cpuinfo) { #分別獲得我們需要的
- @cpustatus=split(/ +/,$line); #每一個(gè)數(shù)值
- }
- $cpuused=$cpustatus[2]+$cpustatus[4];
- $cpuidle=$cpustatus[5];
- print "$cpuused\n"; #輸出兩個(gè)數(shù)值
- print "$cpuidle";
- system ("uptime");
- system ("uname -n");
############### By Vitter :vitter@safechina.net#####################
注意:在腳本里system ("/usr/local/bin/sar -u 1 3|grep Average >cpu_info_file") ,這句話中必須將sar 的全路徑寫全,而不能用system ("sar -u 1 3|grep Average >cpu_info_file") 。因?yàn)閏pu.pl 是由mrtg 調(diào)用,mrtg 不知道你的系統(tǒng)路徑。
我將cpu.pl 腳本放在/usr/local/mrtg/bin 下,執(zhí)行cpu.pl 會(huì)得到下面的結(jié)果:
- [root@intel bin]# ./cpu.pl
- 0
- 100.00
- 12:07am up 1 day, 7:22, 2 users, load average: 0.07, 0.12, 0.09
- TRSB
好,我們需要的數(shù)值已經(jīng)輸出來了,下一步的工作就是要交給mrtg 了,mrtg 是通過一個(gè)配置文件來獲得這兩個(gè)數(shù)值的,通常情況下這個(gè)配置文件是由mrtg 的cfgmaker 命令來生成的, 但這次我們要自己寫這個(gè)配置文件(cpu.cfg) : 這個(gè)配置文件我把他放在/usr/local/mrtg/etc 下,內(nèi)容如下:
- [root@intel etc]# vi cpu.cfg
- WorkDir:/usr/local/apache_1.3.31/htdocs/mrtg/cpu/
- Target[localhost]:`/usr/local/mrtg/bin/cpu.pl`
- Xsize[localhost]: 300
- Ysize[localhost]: 100
- Ytics[localhost]: 10
- MaxBytes[localhost]:100
- Title[localhost]:CPU State
- PageTop[localhost]:CPU State of Vitter-test Server
- ShortLegend[localhost]: %
- YLegend[localhost]: CPU (%)
- Legend1[localhost]: Used
- Legend2[localhost]: Total
- LegendI[localhost]: CPU Used
- LegendO[localhost]: CPU IDEL
- Options[localhost]: growright,gauge,nopercent
下面我們可以執(zhí)行mrtg 了:
- [root@intel etc]#/usr/local/mrtg/bin/mrtg /usr/local/mrtg/etc/cpu.cfg
當(dāng)?shù)谝淮螆?zhí)行時(shí)會(huì)有報(bào)警,執(zhí)行三次,就沒有報(bào)警了。
【編輯推薦】