用MRTG监测Linux系统网络、CPU、内存和硬盘情况
本文讲述的是:用MRTG监测Linux系统网络、CPU、内存和硬盘情况:
3、获得我们需要的关于CPU 和Memory 的数据
1), 获得CPU 的使用率和CPU 的闲置率
为了获得CPU 的这两个数据,我们使用sar –u 1 3 这个命令,
[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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
sar 命令执行后生成如上图所示的数据。我们需要的是三个带下划线的数据。其中:
CPU 的使用率为:%user + %system = 0.00 + 0.33 = 0.33
CPU 的闲置率为:%idle = 99.67
好了只有sar 是不行的,因为mrtg 不能识别这些数据,mrtg 能识别两个数据,所以我们要把0.33 和99.67 传给mrtg,这很容易实现,我用perl 写了一个脚本(cpu.pl)来获得并输出这两个数据:脚本如下
#!/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=; # 读去文件内容
close (CPUINFO); #关闭文件
foreach $line(@cpuinfo) { #分别获得我们需要的
@cpustatus=split(/ +/,$line); #每一个数值
}
$cpuused=$cpustatus[2]+$cpustatus[4];
$cpuidle=$cpustatus[5];
print "$cpuused\n"; #输出两个数值
print "$cpuidle";
system ("uptime");
system ("uname -n");
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
############### 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") 。因为cpu.pl 是由mrtg 调用,mrtg 不知道你的系统路径。
我将cpu.pl 脚本放在/usr/local/mrtg/bin 下,执行cpu.pl 会得到下面的结果:
[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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
好,我们需要的数值已经输出来了,下一步的工作就是要交给mrtg 了,mrtg 是通过一个配置文件来获得这两个数值的,通常情况下这个配置文件是由mrtg 的cfgmaker 命令来生成的, 但这次我们要自己写这个配置文件(cpu.cfg) : 这个配置文件我把他放在/usr/local/mrtg/etc 下,内容如下:
[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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
下面我们可以执行mrtg 了:
[root@intel etc]#/usr/local/mrtg/bin/mrtg /usr/local/mrtg/etc/cpu.cfg
- 1.
- 2.
当第一次执行时会有报警,执行三次,就没有报警了。
【编辑推荐】