程式需求說明,對某一個目錄做 MD5 檢核!並將檢核結果以 E-Mail 方式自動通知!
md5deep
http://md5deep.sourceforge.net/
md5deep.exe -h
md5deep.exe version 4.3 by Jesse Kornblum and Simson Garfinkel.
C:\> md5deep.exe [OPTION]... [FILES]...
See the man page or README.txt file or use -hh for the full list of options
-p <size> - piecewise mode. Files are broken into blocks for hashing
-r - recursive mode. All subdirectories are traversed
-e - show estimated time remaining for each file
-s - silent mode. Suppress all error messages
-z - display file size before hash
-m <file> - enables matching mode. See README/man page
-x <file> - enables negative matching mode. See README/man page
-M and -X are the same as -m and -x but also print hashes of each file
-w - displays which known file generated a match
-n - displays known hashes that did not match any input files
-a and -A add a single hash to the positive or negative matching set
-b - prints only the bare name of files; all path information is omitted
-l - print relative paths for filenames
-t - print GMT timestamp (ctime)
-i/I <size> - only process files smaller/larger than SIZE
-v - display version number and exit
-d - output in DFXML; -u - Escape Unicode; -W FILE - write to FILE.
-j <num> - use num threads (default 2)
-Z - triage mode; -h - help; -hh - full help
#!/usr/bin/perl
#md5filenameok 這個陣列是用來是用來檢核並列出MD5正常的檔案
@md5filenameok=`c:\\perl-shell\\md5deep.exe -r -m c:\\perl-shell\\md5\\syslog.md5 d:\\backup\\*.*`;
#md5filenameoknumber 這個陣列是用來是用來檢核並列出MD5正常的檔案的檔案數量
$md5filenameoknumber=`c:\\perl-shell\\md5deep.exe -r -m c:\\perl-shell\\md5\\syslog.md5 d:\\backup\\*.* | find /c "d:\"`;
#下面這個方式是在 windows command mode 對目錄做出 MD5的檢核檔
#system(`c:\perl-shell\md5deep -l -r d:\backup > c:\perl-shell\md5\syslog.md5`);
#這個陣列是用來是用來檢核並列出MD5異常的檔案
@md5filename=`c:\\perl-shell\\md5deep.exe -r -x c:\\perl-shell\\md5\\syslog.md5 d:\\backup\\*.*`;
#這個陣列是用來是用來檢核並列出MD5異常的檔案的檔案數量
$md5number=`c:\\perl-shell\\md5deep.exe -r -x c:\\perl-shell\\md5\\syslog.md5 d:\\backup\\*.* | find /c "d:\" `;
chomp($md5filenameoknumber);
chomp($md5number);
print '=============== 正常 ===============';
print "\n\n";
print "\n MD5比對正確的檔案清單如下: \n\n @md5filenameok \n";
print "比對正確的檔案數量合計共有 $md5filenameoknumber 個 \n\n";
print '=============== 異常 ===============';
print "\n\n";
print "MD5比對異常的檔案清單如下: \n\n @md5filename \n";
print "比對異常的檔案數量合計共有 $md5number 個 \n ";
@message1="\n MD5比對正確的檔案清單如下: \n\n @md5filenameok \n 比對正確的檔案數量合計共有: $md5filenameoknumber \n\n";
@message2="\n MD5比對異常的檔案清單如下: \n\n @md5filename \n 比對異常的檔案數量合計共有: $md5number \n\n";
#可自行選擇在何種條件才寄出郵件通知!
if ($md5number==0){
print "\n ----> MD5 比對異常的檔案數量為 0 不寄出郵件通知! \n";
$status='[ Normal ]';
get_mail();
}
else {
print " \n ----> MD5 比對異常出郵件通知 \n ";
$status='[ --->Error ]';
get_mail();
}
sub get_mail{
use Encode qw(decode encode_utf8);
use Encode qw(encode);
use MIME::Base64;
use MIME::Lite;
($sec,$min,$hour,$day,$mon,$year,$mday)=localtime(time);
$mon++;
if (length ($mon) == 1) {$mon = '0'.$mon;}
if (length ($day) == 1) {$day = '0'.$day;}
if (length ($hour) == 1) {$hour = '0'.$hour;}
if (length ($min) == 1) {$min = '0'.$min;}
if (length ($sec) == 1) {$sec = '0'.$sec;}
$year+=1900;
$clock=" $status Syslog-Server md5 CheckMail $year/$mon/$day/$hour:$min/";
@foot0=' Syslog-Server D:\BACKUP MD5自動檢查通知程式!';
use Encode qw/from_to/;
from_to(@foot0, "utf8", "big5");
from_to(@message1, "utf8", "big5");
from_to(@message2, "utf8", "big5");
from_to($clock, "utf8", "big5");
$line='=====================================================';
$msg = MIME::Lite->new(
From =>'Syslog-MD5@xrcd2.com.tw',
To =>'xrcd2@xrcd2.com.tw',
Subject => "$clock",
Encoding => 'base64',
Data =>"@foot0 \n\n $line \n\n @message1 \n\n $line\n\n @message2 \n\n $line \n\n"
);
$msg->get_length;
$msg->attr("content-type.charset" => "UTF8");
$msg->send('smtp','smpt.server.ip.address');
print $Mail::SendMail::Error eq "" ? "\n send ok!\n" : $Mail::SendMail::Error;
}
2013年2月25日 星期一
2013年2月23日 星期六
linux Perl 開發環境初使化工作
http://www.ncftp.com/download/
download & install ncftp-client
初使化 cpan ( Perl Module 安裝工具)
#cpan
#cpan -h (說明)
cpan的使用方式
#cpan Module::Name
如
#cpan DBI
或 安裝 cpanm ( Perl Module 安裝工具)
#curl -LO http://bit.ly/cpanm
#chmod +x cpanm
#cp cpanm /bin
#cpanm --help (說明)
#cpanm DBI
[root@centos63 tmp]# cpanm DBIDBI is up to date. (1.623)
[root@centos63 tmp]# cpan DBI CPAN: Storable loaded ok (v2.20)
Going to read '/root/.cpan/Metadata'
Database was generated on Sat, 23 Feb 2013 14:29:04 GMT
DBI is up to date (1.623).
或 cpanp (perl Module 安裝工具 perl 5.10.xx 以後才支援)
#cpanp -i SVK
cpan> install CPANPLUS
[root@centos63 tmp]# cpanp
CPANPLUS::Shell::Default -- CPAN exploration and module installation (v0.9134)
*** Please report bugs to <bug-cpanplus@rt.cpan.org>.
*** Using CPANPLUS::Backend v0.9134.
*** ReadLine support available (try 'i Term::ReadLine::Perl').
*** Type 'p' now to show start up log
Did you know...
You can type 'h' for help and 'q' to exit
CPAN Terminal> h
[General]
h | ? # display help
q # exit
e # exit and reload
v # version information
[Search]
a AUTHOR ... # search by author(s)
m MODULE ... # search by module(s)
f MODULE ... # list all releases of a module
o [ MODULE ... ] # list installed module(s) that aren't up to date
w # display the result of your last search again
[Operations]
i MODULE | NUMBER ... # install module(s), by name or by search number
i URI | ... # install module(s), by URI (ie http://foo.com/X.tgz)
i DIR | ... # install module(s), by path (ie ./Module-1.0)
t MODULE | NUMBER ... # test module(s), by name or by search number
u MODULE | NUMBER ... # uninstall module(s), by name or by search number
d MODULE | NUMBER ... # download module(s)
l MODULE | NUMBER ... # display detailed information about module(s)
r MODULE | NUMBER ... # display README files of module(s)
c MODULE | NUMBER ... # check for module report(s) from cpan-testers
z MODULE | NUMBER ... # extract module(s) and open command prompt in it
[Local Administration]
b # write a bundle file for your configuration
s program [OPT VALUE] # set program locations for this session
s conf [OPT VALUE] # set config options for this session
s mirrors # show currently selected mirrors
s reconfigure # reconfigure settings
s selfupdate # update your CPANPLUS install
s save [user|system] # save settings for this user or systemwide
s edit [user|system] # open configuration file in editor and reload
! EXPR # evaluate a perl statement
p [FILE] # print the error stack (optionally to a file)
x # reload CPAN indices (purges cache)
x --update_source # reload CPAN indices, get fresh source files
[Common Options]
i ... --skiptest # skip tests
i ... --force # force all operations
i ... --verbose # run in verbose mode
[Plugins]
/plugins # list available plugins
/? [PLUGIN NAME] # show usage for (a particular) plugin(s)
CPAN Terminal>
reconfig cpan 的方法
cpan> o conf init
以前會使用 perlcc 去 compile 但那是在 perl 5.8.xx (CentOS Linux 5.xx) 的時代,
在 perl 5.10.xx (CentOS Linux 6.xx )以後,已由 pp 取代了原 perlcc 的功能!
使用方式
#pp -o test test.pl
[root@centos63 tmp]# perl -v
This is perl, v5.10.1 (*) built for i386-linux-thread-multi
Copyright 1987-2009, Larry Wall
Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.
Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl". If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.
[root@centos63 tmp]# pp -version
PAR Packager, version 1.014 (PAR version 1.007)
Copyright 2002-2009 by Audrey Tang <cpan@audreyt.org>
Neither this program nor the associated "parl" program impose any
licensing restrictions on files generated by their execution, in
accordance with the 8th article of the Artistic License:
"Aggregation of this Package with a commercial distribution is
always permitted provided that the use of this Package is embedded;
that is, when no overt attempt is made to make this Package's
interfaces visible to the end user of the commercial distribution.
Such use shall not be construed as a distribution of this Package."
Therefore, you are absolutely free to place any license on the resulting
executable, as long as the packed 3rd-party libraries are also available
under the Artistic License.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself. There is NO warranty; not even for
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[root@centos63 tmp]# cpanm --help
Usage: cpanm [options] Module [...]
Options:
-v,--verbose Turns on chatty output
-q,--quiet Turns off the most output
--interactive Turns on interactive configure (required for Task:: modules)
-f,--force force install
-n,--notest Do not run unit tests
--test-only Run tests only, do not install
-S,--sudo sudo to run install commands
--installdeps Only install dependencies
--showdeps Only display direct dependencies
--reinstall Reinstall the distribution even if you already have the latest version installed
--mirror Specify the base URL for the mirror (e.g. http://cpan.cpantesters.org/)
--mirror-only Use the mirror's index file instead of the CPAN Meta DB
--prompt Prompt when configure/build/test fails
-l,--local-lib Specify the install base to install modules
-L,--local-lib-contained Specify the install base to install all non-core modules
--auto-cleanup Number of days that cpanm's work directories expire in. Defaults to 7
Commands:
--self-upgrade upgrades itself
--info Displays distribution info on CPAN
--look Opens the distribution with your SHELL
-V,--version Displays software version
Examples:
cpanm Test::More # install Test::More
cpanm MIYAGAWA/Plack-0.99_05.tar.gz # full distribution path
cpanm http://example.org/LDS/CGI.pm-3.20.tar.gz # install from URL
cpanm ~/dists/MyCompany-Enterprise-1.00.tar.gz # install from a local file
cpanm --interactive Task::Kensho # Configure interactively
cpanm . # install from local directory
cpanm --installdeps . # install all the deps for the current directory
cpanm -L extlib Plack # install Plack and all non-core deps into extlib
cpanm --mirror http://cpan.cpantesters.org/ DBI # use the fast-syncing mirror
You can also specify the default options in PERL_CPANM_OPT environment variable in the shell rc:
export PERL_CPANM_OPT="--prompt --reinstall -l ~/perl --mirror http://cpan.cpantesters.org"
Type `man cpanm` or `perldoc cpanm` for the more detailed explanation of the options.
個人必裝的是
cpanm Net::Telnet::Cisco
cpanm Mail::Sendmail
cpanm Mail::Sender
cpanm MIME::Lite
cpanm Mail::Builder::Simple
cpanm pp
自動備份 cisco 設備 show run 的 config ( 使用 perl )
使用環境 perl + cisco (ios) + telnet + smtp + 排程
程式碼如下,請視實務需求自行修改!
#!/usr/bin/perl
($sec,$min,$hour,$day,$mon,$year)=localtime(time);
$mon++;
if (length ($mon) == 1) {$mon = '0'.$mon;}
if (length ($day) == 1) {$day = '0'.$day;}
if (length ($hour) == 1) {$hour = '0'.$hour;}
if (length ($min) == 1) {$min = '0'.$min;}
if (length ($sec) == 1) {$sec = '0'.$sec;}
$year+=1900;
$clock="$year$mon$day$hour$min$sec";
$subname='.txt';
$dir='/root/shell/cisco/';
#設備 IP 請務必正確輸入於下面
@cisco=qw
(
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
);
#設備名稱請輸入於下面以方便做為存檔或郵件示別使用
@hostname=qw
(
Switch-1
Switch-2
Switch-3
Switch-4
Router-1
Router-2
Router-3
Router-4
Router-5
);
for ($x=0;$x<=$#cisco;$x++){
print " \n telnet IP $cisco[$x] HostName $hostname[$x] \n";
print " \n Write File Name is $hostname[$x].$clock$subname \n\n ";
$savefile="$dir$hostname[$x].$clock$subname";
print "\n save $savefile \n\n ";
print " \n No. $x IP $cisco[$x] $hostname[$x] Start Sending command .... \n";
# 使用下面這種方式連入 Cisco 設備
get_cisco();
# show run 的存檔作業
open(write_file,">$savefile") or "open file error";
print write_file "@showrun";
close(write_file);
#使用下面這種方式寄信 show run 的資訊會在郵件本文中,
#如不使用~下面 get_mail()前方請加上 #
get_mail();
sleep 5;
#使用下面這種方式寄信 show run 的資訊會變成以附件的方式傳送,
#如不使~用下面 send_config_file() 前方請加上 #
send_config_file();
sleep 5;
}
sub get_cisco{
use Net::Telnet::Cisco;
$session = Net::Telnet::Cisco->new(Host => "$cisco[$x]",Timeout=>'120');
#使用 ID + PWD login 請使用下一行 , 如不使用~下一行前方請加上 #
#$session->login('login', 'password');
#只使有 pwd login 請使用下一行, 如不使用~下一行前方請加上 #
$session->cmd('xxxxxxxxx');
$session->enable('xxxxxxxxx');
@showrun = $session->cmd('show run ');
$session->close;
}
sub get_mail{
use Encode qw(decode encode_utf8);
use Encode qw(encode);
use MIME::Base64;
use MIME::Lite;
$foot0=' Cisco Devices configuration auto backup ';
use Encode qw/from_to/;
from_to($foot0, "utf8", "big5");
from_to(@showrun, "utf8", "big5");
from_to($clock, "utf8", "big5");
$line='=====================================================';
$msg = MIME::Lite->new(
From =>'cisco-show-run@xrcd2.com.tw',
To =>'xrcd2@xrcd2.com.tw',
Subject => "$hostname[$x].$clock.txt",
Encoding => 'base64',
Data =>"$foot0 \n\n $line \n\n @showrun \n\n $line\n\n"
);
$msg->get_length;
$msg->attr("content-type.charset" => "UTF8");
$msg->send('smtp','smtp.server.ip.address');
print $Mail::SendMail::Error eq "" ? "\n send ok!\n" : $Mail::SendMail::Error;
}
sub send_config_file{
use Mail::Sender;
$sender = new Mail::Sender
{smtp => 'smtp.server.ip.address', from => 'showrun@xrcd2.com.tw'};
$sender->MailFile({to => 'xrcd2@xrcd2.com.tw',
subject => "$hostname[$x].$clock$subname",
msg => "$hostname[$x].$clock$subname",
file => "$dir$hostname[$x].$clock$subname"});
}
下圖為以附加檔案方式將 show run 的資訊寄出!
下圖為將 show run 的資訊顯示在郵件本文中!
程式碼如下,請視實務需求自行修改!
#!/usr/bin/perl
($sec,$min,$hour,$day,$mon,$year)=localtime(time);
$mon++;
if (length ($mon) == 1) {$mon = '0'.$mon;}
if (length ($day) == 1) {$day = '0'.$day;}
if (length ($hour) == 1) {$hour = '0'.$hour;}
if (length ($min) == 1) {$min = '0'.$min;}
if (length ($sec) == 1) {$sec = '0'.$sec;}
$year+=1900;
$clock="$year$mon$day$hour$min$sec";
$subname='.txt';
$dir='/root/shell/cisco/';
#設備 IP 請務必正確輸入於下面
@cisco=qw
(
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
);
#設備名稱請輸入於下面以方便做為存檔或郵件示別使用
@hostname=qw
(
Switch-1
Switch-2
Switch-3
Switch-4
Router-1
Router-2
Router-3
Router-4
Router-5
);
for ($x=0;$x<=$#cisco;$x++){
print " \n telnet IP $cisco[$x] HostName $hostname[$x] \n";
print " \n Write File Name is $hostname[$x].$clock$subname \n\n ";
$savefile="$dir$hostname[$x].$clock$subname";
print "\n save $savefile \n\n ";
print " \n No. $x IP $cisco[$x] $hostname[$x] Start Sending command .... \n";
# 使用下面這種方式連入 Cisco 設備
get_cisco();
# show run 的存檔作業
open(write_file,">$savefile") or "open file error";
print write_file "@showrun";
close(write_file);
#使用下面這種方式寄信 show run 的資訊會在郵件本文中,
#如不使用~下面 get_mail()前方請加上 #
get_mail();
sleep 5;
#使用下面這種方式寄信 show run 的資訊會變成以附件的方式傳送,
#如不使~用下面 send_config_file() 前方請加上 #
send_config_file();
sleep 5;
}
sub get_cisco{
use Net::Telnet::Cisco;
$session = Net::Telnet::Cisco->new(Host => "$cisco[$x]",Timeout=>'120');
#使用 ID + PWD login 請使用下一行 , 如不使用~下一行前方請加上 #
#$session->login('login', 'password');
#只使有 pwd login 請使用下一行, 如不使用~下一行前方請加上 #
$session->cmd('xxxxxxxxx');
$session->enable('xxxxxxxxx');
@showrun = $session->cmd('show run ');
$session->close;
}
sub get_mail{
use Encode qw(decode encode_utf8);
use Encode qw(encode);
use MIME::Base64;
use MIME::Lite;
$foot0=' Cisco Devices configuration auto backup ';
use Encode qw/from_to/;
from_to($foot0, "utf8", "big5");
from_to(@showrun, "utf8", "big5");
from_to($clock, "utf8", "big5");
$line='=====================================================';
$msg = MIME::Lite->new(
From =>'cisco-show-run@xrcd2.com.tw',
To =>'xrcd2@xrcd2.com.tw',
Subject => "$hostname[$x].$clock.txt",
Encoding => 'base64',
Data =>"$foot0 \n\n $line \n\n @showrun \n\n $line\n\n"
);
$msg->get_length;
$msg->attr("content-type.charset" => "UTF8");
$msg->send('smtp','smtp.server.ip.address');
print $Mail::SendMail::Error eq "" ? "\n send ok!\n" : $Mail::SendMail::Error;
}
sub send_config_file{
use Mail::Sender;
$sender = new Mail::Sender
{smtp => 'smtp.server.ip.address', from => 'showrun@xrcd2.com.tw'};
$sender->MailFile({to => 'xrcd2@xrcd2.com.tw',
subject => "$hostname[$x].$clock$subname",
msg => "$hostname[$x].$clock$subname",
file => "$dir$hostname[$x].$clock$subname"});
}
下圖為以附加檔案方式將 show run 的資訊寄出!
下圖為將 show run 的資訊顯示在郵件本文中!
2013年2月19日 星期二
cacti linux memory usage template
第一次發現 cacti 的怪現象,使用 cacti 預設的 ucd/net - Memory Usage 的方式,
去 Monitor memory usage 會產生異常,某些主機跑出來的圖示就是怪怪的,
後來在網路上找出其它的 template !
http://forums.cacti.net/viewtopic.php?f=12&t=24501
http://freeccnp-cacti.blogspot.tw/2012/07/memory-usage-linux-graph-template-work.html
但直接匯入 linux memory usage template 並無法使用.
異常的訊息為:
ERROR: invalid rpn expression in: g,e,-,c,-,a,-,1024,*
後來將 CDEFs 改為 cdef=d,b,-,c,-,a,-,1024,* 方可使用.希望不會再出現其它的怪問題了.
正常的圖示如下:
異常的圖示如下:
上圖為 linux memory usage template (ucd/net - Memory Usage (Linux) )
CDEF 修改方式
去 Monitor memory usage 會產生異常,某些主機跑出來的圖示就是怪怪的,
後來在網路上找出其它的 template !
http://forums.cacti.net/viewtopic.php?f=12&t=24501
http://freeccnp-cacti.blogspot.tw/2012/07/memory-usage-linux-graph-template-work.html
但直接匯入 linux memory usage template 並無法使用.
異常的訊息為:
ERROR: invalid rpn expression in: g,e,-,c,-,a,-,1024,*
後來將 CDEFs 改為 cdef=d,b,-,c,-,a,-,1024,* 方可使用.希望不會再出現其它的怪問題了.
正常的圖示如下:
異常的圖示如下:
上圖為 linux memory usage template (ucd/net - Memory Usage (Linux) )
CDEF 修改方式
2013年1月5日 星期六
tomcat Error: Failed to start SNMP adaptor with address
之前在測試 JVM SNMP + JMX 時,皆是以 Tomcat 做為 LAB 的測試標的.
但在使用 /usr/local/tomcat/shutdown.sh 將 tomcat 的服務停止時,
總會產生 tomcat Error: Failed to start SNMP adaptor with address 這樣的訊息.
最後總是直接使用 killall -9 去停止該項服務.最後 google 到 解法.
資料參考 http://www.tikalk.com/java/forums/when-use-tomcat-catalina-opts-instead-java-opts
將 JMX & SNMP 的 JAVA_OPTS 從 /etc/profile.d/java.sh
移到 /usr/local/tomcat/startup.sh
在上方處放上原先設定:
export JAVA_OPTS="-Dcom.sun.management.snmp.port=1610 -Dcom.sun.management.snmp.acl.file=/usr/java/jre/lib/management/snmp.acl -Dcom.sun.management.snmp.interface=0.0.0.0 -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:MaxPermSize=256m -Dcom.sun.management.jmxremote -Djava.rmi.server.hostname=192.168.100.101 -Dcom.sun.management.jmxremote.port=9012 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"
相關文章如下:
Cacti JVM Monitoring template ( Part I )
http://xrcd2.blogspot.tw/2012/12/cacti-jvm-monitoring-template.html
Cacti JVM Monitoring template ( Part II )
http://xrcd2.blogspot.tw/2013/01/cacti-jvm-monitoring-template-part-ii.html
jmx4perl ( JMX access for Perl )
http://xrcd2.blogspot.tw/2013/01/jmx4perl-jmx-access-for-perl.html
JVM Monitor tools
http://visualvm.java.net/
但在使用 /usr/local/tomcat/shutdown.sh 將 tomcat 的服務停止時,
總會產生 tomcat Error: Failed to start SNMP adaptor with address 這樣的訊息.
最後總是直接使用 killall -9 去停止該項服務.最後 google 到 解法.
資料參考 http://www.tikalk.com/java/forums/when-use-tomcat-catalina-opts-instead-java-opts
將 JMX & SNMP 的 JAVA_OPTS 從 /etc/profile.d/java.sh
移到 /usr/local/tomcat/startup.sh
在上方處放上原先設定:
export JAVA_OPTS="-Dcom.sun.management.snmp.port=1610 -Dcom.sun.management.snmp.acl.file=/usr/java/jre/lib/management/snmp.acl -Dcom.sun.management.snmp.interface=0.0.0.0 -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:MaxPermSize=256m -Dcom.sun.management.jmxremote -Djava.rmi.server.hostname=192.168.100.101 -Dcom.sun.management.jmxremote.port=9012 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"
相關文章如下:
Cacti JVM Monitoring template ( Part I )
http://xrcd2.blogspot.tw/2012/12/cacti-jvm-monitoring-template.html
Cacti JVM Monitoring template ( Part II )
http://xrcd2.blogspot.tw/2013/01/cacti-jvm-monitoring-template-part-ii.html
jmx4perl ( JMX access for Perl )
http://xrcd2.blogspot.tw/2013/01/jmx4perl-jmx-access-for-perl.html
JVM Monitor tools
http://visualvm.java.net/
2013年1月3日 星期四
jmx4perl ( JMX access for Perl )
延續 Cacti JVM Monitoring 這個主題.
JMX 是一個標準.可使用 ant 或 jconsole 去取得 JVM 的效能相關數據資料,
以下再介紹使用 webapps agent + perl 的用法,同樣的以 tomcat 為 LAB!
tomcat-connectors
http://tomcat.apache.org/connectors-doc/
#wget http://www.apache.org/dist/tomcat/tomcat-connectors/jk/tomcat-connectors-1.2.37-src.tar.gz
#tar -zvxf tomcat-connectors-1.2.37-src.tar.gz
#cd tomcat-connectors-1.2.37-src/native
#./buildconf.sh
#./configure --with-apxs=/usr/sbin/apxs
#make
#make install
#vi /etc/httpd/conf/httpd.conf
LoadModule jk_module modules/mod_jk.so
#service httpd restart
jolokia (Jolokia is remote JMX with JSON over HTTP)
http://www.jolokia.org/
Jolokia Quickstart
http://www.jolokia.org/tutorial.html
#wget http://www.jolokia.org/dist/1.0.6/jolokia-1.0.6-bin.tar.gz
#tar -zvxf olokia-1.0.6-bin.tar.gz
#cp ./jolokia-1.0.6/agents/jolokia.war /usr/local/tomcat/webapps
#cp ./jolokia-1.0.6/agents/*.jar /usr/local/tomcat/lib
#/usr/local/tomcat/shutdown.sh
#/usr/local/tomcat/startup.sh
test jolokia url
http://jmx.tomcat.server.ip:8080/jolokia/
Perl
install JMX::Jmx4Perl JMX::Jmx4Perl::Alia
#cpan install JMX::Jmx4Perl JMX::Jmx4Perl::Alias
About Jmx4Perl.pm Alias.pm
JMX access for Perl (jmx4perl)
http://search.cpan.org/~roland/jmx4perl/lib/JMX/Jmx4Perl.pm
JMX alias names for jmx4perl
http://search.cpan.org/~roland/jmx4perl-0.71/lib/JMX/Jmx4Perl/Alias.pm
[root@centos63 tmp]# cat jmx.pl
#!/usr/bin/perl
use JMX::Jmx4Perl;
use JMX::Jmx4Perl::Alias;
$jmx1 = JMX::Jmx4Perl->new(url => "http://localhost:8080/jolokia")->get_attribute(MEMORY_HEAP_USED);
$jmx2 = JMX::Jmx4Perl->new(url => "http://localhost:8080/jolokia")->get_attribute(THREAD_COUNT);
print "\n JMX MEMORY_HEAP_USED= $jmx1 \n\n";
print "\n ThreadCount= $jmx2 \n\n";
[root@centos63 tmp]# perl jmx.pl
JMX MEMORY_HEAP_USED= 31746000
ThreadCount= 22
對照 jmx4perl 與 cacti 看到的資料是否一致!

相關文章如下:
Cacti JVM Monitoring template ( Part I )
http://xrcd2.blogspot.tw/2012/12/cacti-jvm-monitoring-template.html
Cacti JVM Monitoring template ( Part II )
http://xrcd2.blogspot.tw/2013/01/cacti-jvm-monitoring-template-part-ii.html
JMX 是一個標準.可使用 ant 或 jconsole 去取得 JVM 的效能相關數據資料,
以下再介紹使用 webapps agent + perl 的用法,同樣的以 tomcat 為 LAB!
tomcat-connectors
http://tomcat.apache.org/connectors-doc/
#wget http://www.apache.org/dist/tomcat/tomcat-connectors/jk/tomcat-connectors-1.2.37-src.tar.gz
#tar -zvxf tomcat-connectors-1.2.37-src.tar.gz
#cd tomcat-connectors-1.2.37-src/native
#./buildconf.sh
#./configure --with-apxs=/usr/sbin/apxs
#make
#make install
#vi /etc/httpd/conf/httpd.conf
LoadModule jk_module modules/mod_jk.so
#service httpd restart
jolokia (Jolokia is remote JMX with JSON over HTTP)
http://www.jolokia.org/
Jolokia Quickstart
http://www.jolokia.org/tutorial.html
#wget http://www.jolokia.org/dist/1.0.6/jolokia-1.0.6-bin.tar.gz
#tar -zvxf olokia-1.0.6-bin.tar.gz
#cp ./jolokia-1.0.6/agents/jolokia.war /usr/local/tomcat/webapps
#cp ./jolokia-1.0.6/agents/*.jar /usr/local/tomcat/lib
#/usr/local/tomcat/shutdown.sh
#/usr/local/tomcat/startup.sh
test jolokia url
http://jmx.tomcat.server.ip:8080/jolokia/
Perl
install JMX::Jmx4Perl JMX::Jmx4Perl::Alia
#cpan install JMX::Jmx4Perl JMX::Jmx4Perl::Alias
About Jmx4Perl.pm Alias.pm
JMX access for Perl (jmx4perl)
http://search.cpan.org/~roland/jmx4perl/lib/JMX/Jmx4Perl.pm
JMX alias names for jmx4perl
http://search.cpan.org/~roland/jmx4perl-0.71/lib/JMX/Jmx4Perl/Alias.pm
[root@centos63 tmp]# cat jmx.pl
#!/usr/bin/perl
use JMX::Jmx4Perl;
use JMX::Jmx4Perl::Alias;
$jmx1 = JMX::Jmx4Perl->new(url => "http://localhost:8080/jolokia")->get_attribute(MEMORY_HEAP_USED);
$jmx2 = JMX::Jmx4Perl->new(url => "http://localhost:8080/jolokia")->get_attribute(THREAD_COUNT);
print "\n JMX MEMORY_HEAP_USED= $jmx1 \n\n";
print "\n ThreadCount= $jmx2 \n\n";
[root@centos63 tmp]# perl jmx.pl
JMX MEMORY_HEAP_USED= 31746000
ThreadCount= 22
對照 jmx4perl 與 cacti 看到的資料是否一致!

相關文章如下:
Cacti JVM Monitoring template ( Part I )
http://xrcd2.blogspot.tw/2012/12/cacti-jvm-monitoring-template.html
Cacti JVM Monitoring template ( Part II )
http://xrcd2.blogspot.tw/2013/01/cacti-jvm-monitoring-template-part-ii.html
Cacti JVM Monitoring template ( Part II )
延續 Cacti JVM Monitoring template 這個主題,
上次已提過 JVM Monitor 的二種型態!
分別為: (1) java snmp (2) jmx
其中的 java snmp 的使用方式請參考 Cacti JVM Monitoring template ( Part I ) URL 如下:
http://xrcd2.blogspot.tw/2012/12/cacti-jvm-monitoring-template.html
接下來要介紹的是,透過 jmx 的方式與 cacti 的運用.
本 LAB 的假設情境為 使用 tomcat 做為 jmx 的 監控目標.
利用 Percona JMX Monitoring Template for Cacti 的方式,進行 jmx monitor
安裝與測試方式參考如下:
http://www.percona.com/doc/percona-monitoring-plugins/cacti/jmx-templates.html
其中的重點是要設定 ant 及 jmx 的使用環境.
請自行參考 Cacti JVM Monitoring template 的 /etc/profile.d/java.sh 的設定.
ant 可於 http://ant.apache.org/ download
#wget http://apache.cdpa.nsysu.edu.tw//ant/binaries/apache-ant-1.8.4-bin.tar.gz
#tar -zvxf apache-ant-1.8.4-bin.tar.gz
#mv apache-ant-1.8.4 /usr/local/ant (配合 /etc/profile.d/java.sh 的設定 )
可透過 ant -version 去測試 ant 是否可以正常使用.
[root@centos bin]# pwd
/usr/local/ant/bin
[root@centos bin]# ./ant -version
Apache Ant(TM) version 1.8.4 compiled on May 22 2012
接下來是 cp /usr/local/tomcat/lib/catalina.jar /home/cactiuser/.ant/lib
download percona-monitoring-plugins-1.0.1.tar.gz 下來使用,URL 如下:
http://www.percona.com/downloads/percona-monitoring-plugins/
解開 percona-monitoring-plugins-1.0.1.tar.gz
在 cacti web 中 使用 Import Templates 將
templates/cacti_host_template_percona_jmx_server_ht_0.8.6i-sver1.0.1.xml 匯入
cp misc/jmx-monitor.xml /home/cacti 供 ss_get_by_ssh.php 使用
cp scripts/ss_get_by_ssh.php /var/www/html/cacti/scripts/ 供 cacti Data Input Methods 使用
而 ss_get_by_ssh.php 則是必須建立 ssh key 方可使用
可參考 [實用的 Cacti Monitoring Template] 一文中的介紹
http://xrcd2.blogspot.tw/2012/05/cacti-monitoring-template.html
上述的檔案中,必須修改的是 ss_get_by_ssh.php & jmx-monitor.xml
請參考下圖:
設定 jmx 不使用 id & pwd 方式即可連入 jmx server
設定 ssh key 的 使用 id & key file
在全數前置作業完成後可透過指令 ant -Djmx.server.port=9012 -e -q -f jmx-monitor.xml
去驗證設定是否正確及運作正常
[root@centos cactiuser]# su - cactiuser
[cactiuser@centos ~]$ ant -Djmx.server.port=9012 -e -q -f jmx-monitor.xml
BUILD FAILED
/home/cactiuser/jmx-monitor.xml:53: javax.management.InstanceNotFoundException: Catalina:type=ThreadPool,name=${jmx.catalina.threadpool.name}
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getMBean(DefaultMBeanServerInterceptor.java:1094)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getAttribute(DefaultMBeanServerInterceptor.java:662)
at com.sun.jmx.mbeanserver.JmxMBeanServer.getAttribute(JmxMBeanServer.java:638)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1431)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:74)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1295)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1387)
at javax.management.remote.rmi.RMIConnectionImpl.getAttribute(RMIConnectionImpl.java:630)
at sun.reflect.GeneratedMethodAccessor50.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:303)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:255)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:233)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:142)
at com.sun.jmx.remote.internal.PRef.invoke(Unknown Source)
at javax.management.remote.rmi.RMIConnectionImpl_Stub.getAttribute(Unknown Source)
at javax.management.remote.rmi.RMIConnector$RemoteMBeanServerConnection.getAttribute(RMIConnector.java:878)
at org.apache.catalina.ant.jmx.JMXAccessorGetTask.jmxGet(JMXAccessorGetTask.java:136)
at org.apache.catalina.ant.jmx.JMXAccessorGetTask.jmxExecute(JMXAccessorGetTask.java:121)
at org.apache.catalina.ant.jmx.JMXAccessorTask.execute(JMXAccessorTask.java:347)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:392)
at org.apache.tools.ant.Target.performTasks(Target.java:413)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExe cutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
at org.apache.tools.ant.Main.runBuild(Main.java:811)
at org.apache.tools.ant.Main.startAnt(Main.java:217)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
Total time: 1 second
及
[cactiuser@centos ~]$php /var/www/html/cacti/scripts/ss_get_by_ssh.php --type jmx --host 127.0.0.1 --items j4,j5,j6,j7,j8,j9,ja,jb
j4:131728176 j5:1037959168 j6:1037959168 j7:25814184 j8:159055872 j9:325058560 ja:52 jb:4096
分別去驗證 jmx-monitor.xml & ss_get_by_ssh.php 的設定
接下來就是在 cacti web 中將 Host Templates \ Percona JMX Server HT 直接拿來使用
實作畫面如下:
上次已提過 JVM Monitor 的二種型態!
分別為: (1) java snmp (2) jmx
其中的 java snmp 的使用方式請參考 Cacti JVM Monitoring template ( Part I ) URL 如下:
http://xrcd2.blogspot.tw/2012/12/cacti-jvm-monitoring-template.html
接下來要介紹的是,透過 jmx 的方式與 cacti 的運用.
本 LAB 的假設情境為 使用 tomcat 做為 jmx 的 監控目標.
利用 Percona JMX Monitoring Template for Cacti 的方式,進行 jmx monitor
安裝與測試方式參考如下:
http://www.percona.com/doc/percona-monitoring-plugins/cacti/jmx-templates.html
其中的重點是要設定 ant 及 jmx 的使用環境.
請自行參考 Cacti JVM Monitoring template 的 /etc/profile.d/java.sh 的設定.
ant 可於 http://ant.apache.org/ download
#wget http://apache.cdpa.nsysu.edu.tw//ant/binaries/apache-ant-1.8.4-bin.tar.gz
#tar -zvxf apache-ant-1.8.4-bin.tar.gz
#mv apache-ant-1.8.4 /usr/local/ant (配合 /etc/profile.d/java.sh 的設定 )
可透過 ant -version 去測試 ant 是否可以正常使用.
[root@centos bin]# pwd
/usr/local/ant/bin
[root@centos bin]# ./ant -version
Apache Ant(TM) version 1.8.4 compiled on May 22 2012
接下來是 cp /usr/local/tomcat/lib/catalina.jar /home/cactiuser/.ant/lib
download percona-monitoring-plugins-1.0.1.tar.gz 下來使用,URL 如下:
http://www.percona.com/downloads/percona-monitoring-plugins/
解開 percona-monitoring-plugins-1.0.1.tar.gz
在 cacti web 中 使用 Import Templates 將
templates/cacti_host_template_percona_jmx_server_ht_0.8.6i-sver1.0.1.xml 匯入
cp misc/jmx-monitor.xml /home/cacti 供 ss_get_by_ssh.php 使用
cp scripts/ss_get_by_ssh.php /var/www/html/cacti/scripts/ 供 cacti Data Input Methods 使用
而 ss_get_by_ssh.php 則是必須建立 ssh key 方可使用
可參考 [實用的 Cacti Monitoring Template] 一文中的介紹
http://xrcd2.blogspot.tw/2012/05/cacti-monitoring-template.html
上述的檔案中,必須修改的是 ss_get_by_ssh.php & jmx-monitor.xml
請參考下圖:
設定 jmx 不使用 id & pwd 方式即可連入 jmx server
設定 ssh key 的 使用 id & key file
在全數前置作業完成後可透過指令 ant -Djmx.server.port=9012 -e -q -f jmx-monitor.xml
去驗證設定是否正確及運作正常
[root@centos cactiuser]# su - cactiuser
[cactiuser@centos ~]$ ant -Djmx.server.port=9012 -e -q -f jmx-monitor.xml
BUILD FAILED
/home/cactiuser/jmx-monitor.xml:53: javax.management.InstanceNotFoundException: Catalina:type=ThreadPool,name=${jmx.catalina.threadpool.name}
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getMBean(DefaultMBeanServerInterceptor.java:1094)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getAttribute(DefaultMBeanServerInterceptor.java:662)
at com.sun.jmx.mbeanserver.JmxMBeanServer.getAttribute(JmxMBeanServer.java:638)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1431)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:74)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1295)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1387)
at javax.management.remote.rmi.RMIConnectionImpl.getAttribute(RMIConnectionImpl.java:630)
at sun.reflect.GeneratedMethodAccessor50.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:303)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:255)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:233)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:142)
at com.sun.jmx.remote.internal.PRef.invoke(Unknown Source)
at javax.management.remote.rmi.RMIConnectionImpl_Stub.getAttribute(Unknown Source)
at javax.management.remote.rmi.RMIConnector$RemoteMBeanServerConnection.getAttribute(RMIConnector.java:878)
at org.apache.catalina.ant.jmx.JMXAccessorGetTask.jmxGet(JMXAccessorGetTask.java:136)
at org.apache.catalina.ant.jmx.JMXAccessorGetTask.jmxExecute(JMXAccessorGetTask.java:121)
at org.apache.catalina.ant.jmx.JMXAccessorTask.execute(JMXAccessorTask.java:347)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:392)
at org.apache.tools.ant.Target.performTasks(Target.java:413)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExe cutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
at org.apache.tools.ant.Main.runBuild(Main.java:811)
at org.apache.tools.ant.Main.startAnt(Main.java:217)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
Total time: 1 second
及
[cactiuser@centos ~]$php /var/www/html/cacti/scripts/ss_get_by_ssh.php --type jmx --host 127.0.0.1 --items j4,j5,j6,j7,j8,j9,ja,jb
j4:131728176 j5:1037959168 j6:1037959168 j7:25814184 j8:159055872 j9:325058560 ja:52 jb:4096
分別去驗證 jmx-monitor.xml & ss_get_by_ssh.php 的設定
接下來就是在 cacti web 中將 Host Templates \ Percona JMX Server HT 直接拿來使用
實作畫面如下:
2012年12月30日 星期日
Cacti JVM Monitoring template ( Part I )
在工作上其他的同事問我如何去查出 Java 程式中的 Thread ??
經由 google 可以查到 透過 JVM 的 SNMP 機制並結合 cacti 可做到這樣的監控功能.
Java snmp 的設定方式請參考下列 URL
http://docs.oracle.com/javase/6/docs/technotes/guides/management/snmp.html
重要詞彙:
Java Virtual Machine (JVM)
Java Management Extensions (JMX)
Remote Method Invocation (RMI)
以下為本 LAB 的設定方式:
[root@centos management]# pwd
/usr/java/jre/lib/management
[root@centos management]# ls -la
total 40
drwxr-xr-x 2 root root 4096 Dec 28 23:27 .
drwxr-xr-x 18 root root 4096 Dec 28 21:55 ..
-rw-r--r-- 1 root root 3998 Nov 14 18:19 jmxremote.access
-r--r--r-- 1 root root 2856 Nov 14 18:19 jmxremote.password.template
-rw-r--r-- 1 root root 14097 Nov 14 18:19 management.properties
-r-------- 1 root root 3355 Dec 28 23:16 snmp.acl
-r--r--r-- 1 root root 3376 Nov 14 18:19 snmp.acl.template
[root@centos management]# cat snmp.acl
acl = {
{
communities = public
access = read-only
managers = localhost
}
}
下方的 java profile 設定分為三段
(1)啟用 jvm snmp 使用設定
(2)設定 jvm RAM 使用設定
(3)啟用 jmx 使用設定 (透過 jconsole 去 monitor jvm )
[root@centos profile.d]# pwd
/etc/profile.d
[root@centos profile.d]# cat java.sh
JAVA_HOME=/usr/java
ANT_HOME=/usr/local/ant
CLASSPATH=.:$JAVA_HOME/lib/tools.jar:/usr/java/jre/lib/management-agent.jar:/usr/local/ant/lib/ant.jar
PATH=$JAVA_HOME/bin:$PATH:$ANT_HOME/bin
export JAVA_HOME CLASSPATH PATH ANT_HOME
export JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.snmp.port=1610 -Dcom.sun.management.snmp.acl.file=/usr/java/jre/lib/management/snmp.acl -Dcom.sun.management.snmp.interface=0.0.0.0 -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:MaxPermSize=256m -Dcom.sun.management.jmxremote -Djava.rmi.server.hostname=192.168.100.101 -Dcom.sun.management.jmxremote.port=9012 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"
檢查 jvm snmp & jmx 是否正常 Listen
[root@centos snmp_queries]# netstat -anp | grep java
tcp 0 0 ::ffff:127.0.0.1:8005 :::* LISTEN 1477/java
tcp 0 0 :::50023 :::* LISTEN 1477/java
tcp 0 0 :::8009 :::* LISTEN 1477/java
tcp 0 0 :::8080 :::* LISTEN 1477/java
tcp 0 0 :::49043 :::* LISTEN 1477/java
tcp 0 0 :::9012 :::* LISTEN 1477/java
udp 0 0 :::1610 :::* 1477/java
驗證 snmp 的服務是否正常
[root@centos snmp_queries]#snmpwalk -v2c -c public localhost system
SNMPv2-MIB::sysDescr.0 = STRING: Linux centos 2.6.32-279.19.1.el6.i686 #1 SMP Wed Dec 19 04:30:58 UTC 2012 i686
SNMPv2-MIB::sysObjectID.0 = OID: NET-SNMP-MIB::netSnmpAgentOIDs.10
DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (117485) 0:19:34.85
SNMPv2-MIB::sysContact.0 = STRING: Root <root@localhost> (configure /etc/snmp/snmp.local.conf)
SNMPv2-MIB::sysName.0 = STRING: centos
SNMPv2-MIB::sysLocation.0 = STRING: Unknown (edit /etc/snmp/snmpd.conf)
SNMPv2-MIB::sysORLastChange.0 = Timeticks: (6) 0:00:00.06
SNMPv2-MIB::sysORID.1 = OID: SNMP-MPD-MIB::snmpMPDMIBObjects.3.1.1
SNMPv2-MIB::sysORID.2 = OID: SNMP-USER-BASED-SM-MIB::usmMIBCompliance
SNMPv2-MIB::sysORID.3 = OID: SNMP-FRAMEWORK-MIB::snmpFrameworkMIBCompliance
SNMPv2-MIB::sysORID.4 = OID: SNMPv2-MIB::snmpMIB
SNMPv2-MIB::sysORID.5 = OID: TCP-MIB::tcpMIB
SNMPv2-MIB::sysORID.6 = OID: IP-MIB::ip
SNMPv2-MIB::sysORID.7 = OID: UDP-MIB::udpMIB
SNMPv2-MIB::sysORID.8 = OID: SNMP-VIEW-BASED-ACM-MIB::vacmBasicGroup
SNMPv2-MIB::sysORDescr.1 = STRING: The MIB for Message Processing and Dispatching.
SNMPv2-MIB::sysORDescr.2 = STRING: The MIB for Message Processing and Dispatching.
SNMPv2-MIB::sysORDescr.3 = STRING: The SNMP Management Architecture MIB.
SNMPv2-MIB::sysORDescr.4 = STRING: The MIB module for SNMPv2 entities
SNMPv2-MIB::sysORDescr.5 = STRING: The MIB module for managing TCP implementations
SNMPv2-MIB::sysORDescr.6 = STRING: The MIB module for managing IP and ICMP implementations
SNMPv2-MIB::sysORDescr.7 = STRING: The MIB module for managing UDP implementations
SNMPv2-MIB::sysORDescr.8 = STRING: View-based Access Control Model for SNMP.
SNMPv2-MIB::sysORUpTime.1 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.2 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.3 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.4 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.5 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.6 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.7 = Timeticks: (5) 0:00:00.05
SNMPv2-MIB::sysORUpTime.8 = Timeticks: (6) 0:00:00.06
[root@centos snmp_queries]# snmpget -v2c -c public localhost SNMPv2-MIB::sysDescr.0
SNMPv2-MIB::sysDescr.0 = STRING: Linux centos 2.6.32-279.19.1.el6.i686 #1 SMP Wed Dec 19 04:30:58 UTC 2012 i686
[root@centos snmp_queries]#
JVM SNMP MIB 參考的 URL
http://ipmsupport.solarwinds.com/mibs/JVM-MANAGEMENT-MIB/oids.aspx
http://support.ipmonitor.com/mibs/JVM-MANAGEMENT-MIB/oids.aspx
JVM Thread Count MIB
1.3.6.1.4.1.42.2.145.3.163.1.1.3.1.0
透過使用 snmp proxy 的方式
[root@centos snmp_queries]# snmpget -v2c -c public localhost 1.3.6.1.4.1.42.2.145.3.163.1.1.3.1.0
SNMPv2-SMI::enterprises.42.2.145.3.163.1.1.3.1.0 = Gauge32: 19
vi /etc/snmp/snmpd.conf
mibs +JVM-MANAGEMENT-MIB
proxy -v 2c -c public localhost:1610 .1.3.6.1.4.1.42
修改必須重啟 snmpd
不透過使用 snmp proxy 的方式
[root@centos snmp_queries]
#snmpget -v2c -c public localhost:1610 1.3.6.1.4.1.42.2.145.3.163.1.1.3.1.0
SNMPv2-SMI::enterprises.42.2.145.3.163.1.1.3.1.0 = Gauge32: 19
需修改 Data Templates snmp port 為 1610
Another JVM Monitoring template
http://forums.cacti.net/post-112268.html
修改 Data Templates snmp port 為 1610
jconsole test demo
jconsole test demo
cacti monitor 與 jconsole 實際運作時的對照如下
2012年12月22日 星期六
rrdtool 用法與 cacti 設定對照 ( Part III )
延續 rrdtool 用法與 cacti 設定對照( Part II )
http://xrcd2.blogspot.tw/2012/12/rrdtool-cacti-part-ii.html
經過前二篇的介紹我們已經知道 cacti & rrdtool 的設定方式(原理)
與 rrdtool 的關連性,接下來我要介紹的是如何利用既有 cacti 的
rrd 檔,再轉成如 MRTG 般的圖示,
如下圖示我們可以透過 Cacti Turn On Graph Debug Mode 將 圖檔
的 rrdtool 構成語法,顯示在 WEB 上
rrdtool graph 產出語法如下:
/usr/bin/rrdtool graph - \
--imgformat=PNG \
--start=-86400 \
--end=-300 \
--title='cacti - Traffic - eth0' \
--rigid \
--base=1000 \
--height=120 \
--width=500 \
--alt-autoscale-max \
--lower-limit='0' \
--vertical-label='bits per second' \
--slope-mode \
--font TITLE:10: \
--font AXIS:7: \
--font LEGEND:8: \
--font UNIT:7: \
DEF:a="/var/www/html/cacti/rra/cacti_traffic_in_21.rrd":'traffic_in':AVERAGE \
DEF:b="/var/www/html/cacti/rra/cacti_traffic_in_21.rrd":'traffic_out':AVERAGE \
CDEF:cdefa='a,8,*' \
CDEF:cdefe='b,8,*' \
AREA:cdefa#00CF00FF:"Inbound" \
GPRINT:cdefa:LAST:" Current\:%8.2lf %s" \
GPRINT:cdefa:AVERAGE:"Average\:%8.2lf %s" \
GPRINT:cdefa:MAX:"Maximum\:%8.2lf %s\n" \
LINE1:cdefe#002A97FF:"Outbound" \
GPRINT:cdefe:LAST:"Current\:%8.2lf %s" \
GPRINT:cdefe:AVERAGE:"Average\:%8.2lf %s" \
GPRINT:cdefe:MAX:"Maximum\:%8.2lf %s\n"
接下來依樣 山寨 為 perl rrdtool 的語法,產出如 cacti 中的 web 圖示
#!/usr/bin/perl -w
use RRDs;
$rrd='/var/www/html/cacti/rra/cacti_traffic_in_21.rrd';
print "Start Creating Graph \n";
RRDs::graph "/var/www/html/eth0.png",
"--imgformat","PNG",
"--start", -86400,
"--end", -300,
"--title=cacti - Traffic - eth0",
"--rigid",
"--base=1000",
"--height=120",
"--width=500",
"--alt-autoscale-max",
"--lower-limit=0",
"--vertical-label=bits per second",
"--slope-mode",
"--font","TITLE:10",
"--font","AXIS:7",
"--font","LEGEND:8:",
"--font","UNIT:7",
"DEF:a=$rrd:traffic_in:AVERAGE",
"DEF:b=$rrd:traffic_out:AVERAGE",
"CDEF:ab=a,8,\*",
"CDEF:bb=b,8,\*",
"AREA:ab#00FF00:Inbound ",
"GPRINT:ab:LAST:Current\\:%8.2lf %s ",
"GPRINT:ab:AVERAGE:avg\\:%8.2lf %s",
"GPRINT:ab:MAX:max\\:%8.2lf %s \\n",
"LINE:bb#0000FF:Outbound",
"GPRINT:bb:LAST:Current\\:%8.2lf %s ",
"GPRINT:bb:AVERAGE:avg\\:%8.2lf %s",
"GPRINT:bb:MAX:max\\:%8.2lf %s \\n",
"COMMENT:Designer XRCD2" ,
;
if ($ERROR = RRDs::error) {
die "ERROR: $ERROR\n";
};
print "END \n";
當然也可以按照自己的想法加以變化如
或者
#!/usr/bin/perl -w
use RRDs;
$rrd='/var/www/html/cacti/rra/cacti_traffic_in_21.rrd';
print "Start Creating Graph \n";
RRDs::graph "/var/www/html/before4hour.png",
"--imgformat","PNG",
"--start", -14700, # 4*60*60+300 (換算成秒數的算法)
"--end", -300,
"--title=cacti - Traffic - eth0 (before4hour)",
"--rigid",
"--base=1000",
"--height=120",
"--width=500",
"--alt-autoscale-max",
"--lower-limit=0",
"--vertical-label=bits per second",
"--slope-mode",
"--font","TITLE:10",
"--font","AXIS:7",
"--font","LEGEND:8:",
"--font","UNIT:7",
"DEF:a=$rrd:traffic_in:AVERAGE",
"DEF:b=$rrd:traffic_out:AVERAGE",
"CDEF:ab=a,8,\*",
"CDEF:bb=b,8,\*",
"AREA:ab#00FF00:Inbound ",
"GPRINT:ab:LAST:Current\\:%8.2lf %s ",
"GPRINT:ab:AVERAGE:avg\\:%8.2lf %s",
"GPRINT:ab:MAX:max\\:%8.2lf %s \\n",
"LINE:bb#0000FF:Outbound",
"GPRINT:bb:LAST:Current\\:%8.2lf %s ",
"GPRINT:bb:AVERAGE:avg\\:%8.2lf %s",
"GPRINT:bb:MAX:max\\:%8.2lf %s \\n",
"COMMENT:Designer XRCD2" ,
;
if ($ERROR = RRDs::error) {
die "ERROR: $ERROR\n";
};
print "END \n";
接下來就是自由變化的型態了,都已經變成圖檔了.要放在 web 變 mrtg 也行.
( 山寨 mrtg 示意畫面)
或者是更進階的自動產出 E-Mail 報表也行 (如日報 週報 月報 季報 年報...)也行
上面圖示中的 自動產出 E-Mail 報表 郵件程式抄改自
http://search.cpan.org/~teddy/Mail-Builder-Simple-0.16/lib/Mail/Builder/Simple.pm
#/usr/bin/perl
use Mail::Builder::Simple;
$png=' <img src="cid:logo" alt="logo"> ';
$mail = Mail::Builder::Simple->new;
$mail->image->add('/var/www/html/eth0.png', 'logo');
$mail->send(
mail_client => { mailer => 'SMTP' ,mailer_args => {host => 'smtp.server.ip.address'}},
from => ['cacti@xrcd2.com.tw', 'My Name'],
to => ['mis@xrcd2.com.tw', 'Your Name'],
subject => 'The subject with UTF-8 chars',
plaintext => "Hello,\n\nHow are you?\n\n",
htmltext => "<h1>Hello,</h1> <p>How are you?</p><p> 報表在下面看看吧 <p><p> $png </p>",
#attachment => 'file.pdf',
#image => 'demo.png',
priority => 1,
mailer => 'My Mailer 0.01',
);
當然我們也可以透過玩 CDEF 的運算去玩變形的花樣
正常版
變形版
print "Start Creating Graph \n";
RRDs::graph "/srv/www/htdocs/demo-v2.png",
"--title=Traffic Demo V2",
"--start", $begin,
"--end", $endtime,
"--interlace",
"--imgformat","PNG",
"--width=500",
"--height=120",
"--vertical-label=bps",
"DEF:a=$rrd:a:AVERAGE",
"DEF:b=$rrd:b:AVERAGE",
"CDEF:ab=a,8,\*",
"CDEF:bb=b,8,\*",
"AREA:ab#00FF00: Traffic_In",
"COMMENT:\\n",
"GPRINT:ab:MIN: min\\: %8.2lf %s",
"GPRINT:ab:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:ab:MAX: max\\: %8.2lf %s",
"GPRINT:ab:LAST: last\\: %8.2lf %s",
"COMMENT:\\n",
"LINE:bb#0000FF: Traffic_Out",
"COMMENT:\\n",
"GPRINT:bb:MIN: min\\: %8.2lf %s",
"GPRINT:bb:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:bb:MAX: max\\: %8.2lf %s",
"GPRINT:bb:LAST: last\\: %8.2lf %s ",
"HRULE:100000#FF0000: value > 100000 Warning",
"COMMENT:\\n",
"COMMENT:Last Updated $clock" ,
;
if ($ERROR = RRDs::error) {
die "ERROR: $ERROR\n";
};
print "END \n";
變形版部份程式範列 ( perl )
print "Start Creating Graph \n";
RRDs::graph "/srv/www/htdocs/demo-v3.png",
"--title=Traffic Demo V3",
"--start", $begin,
"--end", $endtime,
"--interlace",
"--imgformat","PNG",
"--width=500",
"--height=120",
"--vertical-label=bps",
"DEF:a=$rrd:a:AVERAGE",
"DEF:b=$rrd:b:AVERAGE",
"CDEF:ab=a,8,\*",
"CDEF:bb=b,-8,\*",
"CDEF:bc=b,8,\*",
"AREA:ab#99FF99: Traffic_In",
"LINE:ab#00DD00:Peak",
"COMMENT:\\n",
"GPRINT:ab:MIN: min\\: %8.2lf %s",
"GPRINT:ab:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:ab:MAX: max\\: %8.2lf %s",
"GPRINT:ab:LAST: last\\: %8.2lf %s",
"COMMENT:\\n",
"AREA:bb#00E5EE: Traffic_Out",
"LINE:bb#0000FF:Peak",
"COMMENT:\\n",
"GPRINT:bc:MIN: min\\: %8.2lf %s",
"GPRINT:bc:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:bc:MAX: max\\: %8.2lf %s",
"GPRINT:bc:LAST: last\\: %8.2lf %s ",
"HRULE:100000#FF0000: value > 100000 Warning",
"COMMENT:\\n",
"COMMENT:Last Updated $clock" ,
;
if ($ERROR = RRDs::error) {
die "ERROR: $ERROR\n";
};
print "END \n";
透過這一篇的介紹,應該可以透過 DIY 的小程式,將線上運行中的 cacti 產出如
mrtg 的網頁, 也可以 DIY 出 簡單網管 E-Mail 報表!
最後再想想透過連續這三篇介紹,將基礎打好,觀念搞清楚,再去玩 cacti 會更
了解一些,最簡單的說 cacti 只是用來簡化 rrdtool 的操作與設定.
但 cacti 的功能與強大之處,不是三言兩語可以說介紹完的. rrdtool 也是如此!
接下來如有時間我會再介紹 cacti 的 安裝.操作與使用....待續....
本 LAB 使用 cacti + rrdtool + perl + Mail 這四個要素.缺一不可.
Base on ( LAMP +P+R)
Linux Apache Mysql PHP Perl rrdtool !
2012年12月7日 星期五
rrdtool 用法與 cacti 設定對照 ( Part II )
延續 rrdtool 用法與 cacti 設定對照(Part I)
http://xrcd2.blogspot.tw/2012/11/rrdtool-cacti.html
簡單的說明關於 rrdtool 的使用方式(步驟).
(1)RRD檔案的產出,必需先經由 rrdtoo create filename.rrd ..
過程產出 rrdtool的資料庫架構
(2)update RRD檔的資料,透過 rrdtool update filename.rrd ...
方式將新增加的資料加入資料庫中.
(3)歷史軌跡的圖示資料,透過使用 rrdtool graph fileame.png ...
將圖示產出.
Perl 範例程式
#!/usr/bin/perl -w
use RRDs;
$start=time;
$rrd="/srv/www/perl-lib/demo.rrd";
$log="/srv/www/perl-lib/demo.log";
#建立RRDs的基本資料庫的格式(只需執行一次即可)
print "Check RRD Files \n";
if(!(-e "$rrd")){
print "start creating RRDs_Base \n";
RRDs::create ($rrd, "--start",$start-1, "--step",300,
"DS:a:COUNTER:600:U:U",
"DS:b:COUNTER:600:U:U",
"RRA:MIN:0.5:1:600",
"RRA:MIN:0.5:6:700",
"RRA:MIN:0.5:24:775",
"RRA:MIN:0.5:288:797",
"RRA:AVERAGE:0.5:1:600",
"RRA:AVERAGE:0.5:6:700",
"RRA:AVERAGE:0.5:24:775",
"RRA:AVERAGE:0.5:288:797",
"RRA:MAX:0.5:1:600",
"RRA:MAX:0.5:6:700",
"RRA:MAX:0.5:24:775",
"RRA:MAX:0.5:288:797"
);
$ERROR = RRDs::error;
die "$0: unable to create `$rrd': $ERROR\n" if $ERROR;
}
#當資料庫已存在的情況下,就開始新增歷史軌跡資料
# (不斷的累積該資料但受限RRDs的基本運作模式有一定存放筆數與循環)
else {
print " RRDs File Exist \n";
print " Update RRDs Data \n";
$uptime=time;
get_snmp_traffic();
print "$uptime $traffic_in $traffic_out \n";
RRDs::update ("$rrd","$uptime:$traffic_in:$traffic_out");
if ($ERROR = RRDs::error) {
die "$0: unable to update `$rrd': $ERROR\n";
}
}
#假設未建立RRDs檔,則歷史軌跡的圖示資料結束時間為現在時間加1,
#用於產出圖示時間區間用
if (!(-e "rrd")){
$uptime=$start+1;
}
#產出圖示的 Last Updated 日期與時間資料
get_time();
print "Start_time $start \n";
print "Up_time $uptime \n";
#建立log檔,並將 TimeStamp 初始時間寫入log檔
if (!(-e "$log")){
print "Write RRDs time log file \n";
open(write_log,"> $log");
print write_log "$start";
close(write_log);
}
#如果log檔案存在,就將 TimeStamp 初始時間讀出
if (-e "$log") {
print "Open Log File\n";
open (open_file,"$log");
$start=<open_file>;
close(open_file);
}
print "Start_time $start \n";
print "Up_time $uptime \n";
#建立圖示從log記錄時間直到當下時間.一直不間斷的繪製下去
#(受限RRDs的基本運作模式有一定存放筆數與循環)
#一般而言常見的類型為 每日.每週.每月.每年等等...有一定的圖示格式
print "Start Creating Graph \n";
RRDs::graph "/srv/www/htdocs/demo.png",
"--title=Traffic Demo",
"--start", $start,
"--end", $uptime,
"--interlace",
"--imgformat","PNG",
"--width=500",
"--height=120",
"--vertical-label=bps",
"DEF:a=$rrd:a:AVERAGE",
"DEF:b=$rrd:b:AVERAGE",
"CDEF:ab=a,8,\*",
"CDEF:bb=b,8,\*",
"AREA:ab#00FF00: Traffic_In",
"GPRINT:ab:MIN: min\\: %8.2lf %s",
"GPRINT:ab:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:ab:MAX: max\\: %8.2lf %s",
"GPRINT:ab:LAST: last\\: %8.2lf %s",
"LINE:bb#0000FF: Traffic_Out",
"GPRINT:bb:MIN: min\\: %8.2lf %s",
"GPRINT:bb:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:bb:MAX: max\\: %8.2lf %s",
"GPRINT:bb:LAST: last\\: %8.2lf %s",
"COMMENT:\\n",
"COMMENT:Last Updated $clock" ,
;
if ($ERROR = RRDs::error) {
die "ERROR: $ERROR\n";
};
print "END \n";
#透過 snmpget 的方式將 eth0 的流量取出 (DS[Data Source]的資料來源)
sub get_snmp_traffic{
use Net::SNMP;
$traffic_eth0_in_oid = '1.3.6.1.2.1.2.2.1.10.2';
$traffic_eth0_out_oid='1.3.6.1.2.1.2.2.1.16.2';
($session,$error) = Net::SNMP->session(Hostname => "localhost",Community => "public");
die "session error: $error" unless ($session);
$result_in = $session->get_request("$traffic_eth0_in_oid ");
$result_out = $session->get_request("$traffic_eth0_out_oid ");
die "request error: ".$session->error unless (defined $result_in);
$session->close;
$traffic_in=$result_in->{"$traffic_eth0_in_oid"};
$traffic_out=$result_out->{"$traffic_eth0_out_oid"};
}
#將時間轉成 西元年月日 時:分:秒
sub get_time {
($sec,$min,$hour,$day,$mon,$year)=localtime(time);
$mon++;
if (length ($mon) == 1) {$mon = '0'.$mon;}
if (length ($day) == 1) {$day = '0'.$day;}
if (length ($hour) == 1) {$hour = '0'.$hour;}
if (length ($min) == 1) {$min = '0'.$min;}
if (length ($sec) == 1) {$sec = '0'.$sec;}
$year+=1900;
$clock="$year$mon$day $hour\\:$min\\:$sec";
}
每五分鐘執行一次即可
==============================================================
最後30分鐘的圖示產出程式範例
#!/usr/bin/perl -w
use RRDs;
$log="/srv/www/perl-lib/demo.log";
$rrd="/srv/www/perl-lib/demo.rrd";
print "Open Log File\n";
open (open_file,"$log");
$start=<open_file>;
close(open_file);
$now=time;
$start_date = localtime($start);
$begin=int($now-1800);#圖示開始時間:以30分鐘以前的時間取樣(1800秒)
$endtime=int($now+1);#圖示結束時間:現在時間+1的時間取樣
$begin_date= localtime($begin);
$end_date= localtime($endtime);
print " RRD記錄初始時間為 $start_date\n";
print "圖示記錄初始時間為 $begin_date\n";
print "圖示記錄結束時間為 $end_date\n";
print "Start_time $start \n";
print "Begin_time $begin \n";
print " endtime $endtime \n";
get_time();
sleep 20;
print "Start Creating Graph \n";
RRDs::graph "/srv/www/htdocs/demo30min.png",
"--title=Demo Traffic Last Half Hour ",
"--start", $begin,
"--end", $endtime,
"--interlace",
"--imgformat","PNG",
"--width=500",
"--height=120",
"--vertical-label=bps",
"DEF:a=$rrd:a:AVERAGE",
"DEF:b=$rrd:b:AVERAGE",
"CDEF:ab=a,8,\*",
"CDEF:bb=b,8,\*",
"AREA:ab#00FF00: Traffic_In ",
"GPRINT:ab:MIN: min\\: %8.2lf %s",
"GPRINT:ab:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:ab:MAX: max\\: %8.2lf %s",
"GPRINT:ab:LAST: last\\: %8.2lf %s",
"COMMENT:\\n",
"LINE:bb#0000FF: Traffic_Out",
"GPRINT:bb:MIN: min\\: %8.2lf %s",
"GPRINT:bb:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:bb:MAX: max\\: %8.2lf %s",
"GPRINT:bb:LAST: last\\: %8.2lf %s",
"COMMENT:\\n",
"COMMENT:Last Updated $clock" ,
;
if ($ERROR = RRDs::error) {
die "ERROR: $ERROR\n";
};
print "END \n";
sub get_time {
($sec,$min,$hour,$day,$mon,$year)=localtime(time);
$mon++;
if (length ($mon) == 1) {$mon = '0'.$mon;}
if (length ($day) == 1) {$day = '0'.$day;}
if (length ($hour) == 1) {$hour = '0'.$hour;}
if (length ($min) == 1) {$min = '0'.$min;}
if (length ($sec) == 1) {$sec = '0'.$sec;}
$year+=1900;
$clock="$year$mon$day $hour\\:$min\\:$sec";
}
每五分鐘執行一次即可 (30分鐘程式範列圖示如下)
=============================================
對照 cacti 程式作業分解
(1)選擇 DS(Data Source) 來源 (如某主機的網管流量)
(2)建立 rrd 資料庫
(3)更新歷史軌跡資料庫
(4)產出歷史軌跡的圖示
cacti 尚未建立 rrd 資料庫
已建立 rrd 資料庫與圖示(但還沒有DS資料)
CDEFs
GPRINT
RRA
Data Source Type
Graph Traffic
cacti [ Last Half Hour ] [DS資料來源為最後30分鐘的數據]
Perl code style V.S cacti ( Perl 山寨版圖示 與 cacti 正版圖示 對照如下 )
其它圖示範例
未經 GPRINT 正規化(只顯示數值大小,沒自動換成以 K...為顯示單位)
再次重申,我還是會推薦大家使用 OpenSource 的網管程式.如 cacti or zabbix or opennms
Zenoss Core or Nagios
如果公司有錢的話.那就看看
HP OpenView or IBM Tivoli or Solarwinds or WhatsUp or CiscoWorks .....
OpenSource 還是有一定的極限在...廢話不過也是實話....
關於 snmpget 的技法可參考下列文章
再論 SNMP OIDs
http://xrcd2.blogspot.tw/2012/10/snmp-oid.html
利用SNMP OIDs 加入 Zabbix 監控
http://xrcd2.blogspot.tw/2012/10/snmp-oids-zabbix.html
關於網管系統的建置可參考
Cacti + XSMS_API (SOAP) (自行客製化 Cacti + SMS )
http://xrcd2.blogspot.tw/2012/05/cacti-xsmsapi-soap-cacti-sms.html
http://xrcd2.blogspot.tw/2012/11/rrdtool-cacti.html
簡單的說明關於 rrdtool 的使用方式(步驟).
(1)RRD檔案的產出,必需先經由 rrdtoo create filename.rrd ..
過程產出 rrdtool的資料庫架構
(2)update RRD檔的資料,透過 rrdtool update filename.rrd ...
方式將新增加的資料加入資料庫中.
(3)歷史軌跡的圖示資料,透過使用 rrdtool graph fileame.png ...
將圖示產出.
Perl 範例程式
#!/usr/bin/perl -w
use RRDs;
$start=time;
$rrd="/srv/www/perl-lib/demo.rrd";
$log="/srv/www/perl-lib/demo.log";
#建立RRDs的基本資料庫的格式(只需執行一次即可)
print "Check RRD Files \n";
if(!(-e "$rrd")){
print "start creating RRDs_Base \n";
RRDs::create ($rrd, "--start",$start-1, "--step",300,
"DS:a:COUNTER:600:U:U",
"DS:b:COUNTER:600:U:U",
"RRA:MIN:0.5:1:600",
"RRA:MIN:0.5:6:700",
"RRA:MIN:0.5:24:775",
"RRA:MIN:0.5:288:797",
"RRA:AVERAGE:0.5:1:600",
"RRA:AVERAGE:0.5:6:700",
"RRA:AVERAGE:0.5:24:775",
"RRA:AVERAGE:0.5:288:797",
"RRA:MAX:0.5:1:600",
"RRA:MAX:0.5:6:700",
"RRA:MAX:0.5:24:775",
"RRA:MAX:0.5:288:797"
);
$ERROR = RRDs::error;
die "$0: unable to create `$rrd': $ERROR\n" if $ERROR;
}
#當資料庫已存在的情況下,就開始新增歷史軌跡資料
# (不斷的累積該資料但受限RRDs的基本運作模式有一定存放筆數與循環)
else {
print " RRDs File Exist \n";
print " Update RRDs Data \n";
$uptime=time;
get_snmp_traffic();
print "$uptime $traffic_in $traffic_out \n";
RRDs::update ("$rrd","$uptime:$traffic_in:$traffic_out");
if ($ERROR = RRDs::error) {
die "$0: unable to update `$rrd': $ERROR\n";
}
}
#假設未建立RRDs檔,則歷史軌跡的圖示資料結束時間為現在時間加1,
#用於產出圖示時間區間用
if (!(-e "rrd")){
$uptime=$start+1;
}
#產出圖示的 Last Updated 日期與時間資料
get_time();
print "Start_time $start \n";
print "Up_time $uptime \n";
#建立log檔,並將 TimeStamp 初始時間寫入log檔
if (!(-e "$log")){
print "Write RRDs time log file \n";
open(write_log,"> $log");
print write_log "$start";
close(write_log);
}
#如果log檔案存在,就將 TimeStamp 初始時間讀出
if (-e "$log") {
print "Open Log File\n";
open (open_file,"$log");
$start=<open_file>;
close(open_file);
}
print "Start_time $start \n";
print "Up_time $uptime \n";
#建立圖示從log記錄時間直到當下時間.一直不間斷的繪製下去
#(受限RRDs的基本運作模式有一定存放筆數與循環)
#一般而言常見的類型為 每日.每週.每月.每年等等...有一定的圖示格式
print "Start Creating Graph \n";
RRDs::graph "/srv/www/htdocs/demo.png",
"--title=Traffic Demo",
"--start", $start,
"--end", $uptime,
"--interlace",
"--imgformat","PNG",
"--width=500",
"--height=120",
"--vertical-label=bps",
"DEF:a=$rrd:a:AVERAGE",
"DEF:b=$rrd:b:AVERAGE",
"CDEF:ab=a,8,\*",
"CDEF:bb=b,8,\*",
"AREA:ab#00FF00: Traffic_In",
"GPRINT:ab:MIN: min\\: %8.2lf %s",
"GPRINT:ab:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:ab:MAX: max\\: %8.2lf %s",
"GPRINT:ab:LAST: last\\: %8.2lf %s",
"LINE:bb#0000FF: Traffic_Out",
"GPRINT:bb:MIN: min\\: %8.2lf %s",
"GPRINT:bb:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:bb:MAX: max\\: %8.2lf %s",
"GPRINT:bb:LAST: last\\: %8.2lf %s",
"COMMENT:\\n",
"COMMENT:Last Updated $clock" ,
;
if ($ERROR = RRDs::error) {
die "ERROR: $ERROR\n";
};
print "END \n";
#透過 snmpget 的方式將 eth0 的流量取出 (DS[Data Source]的資料來源)
sub get_snmp_traffic{
use Net::SNMP;
$traffic_eth0_in_oid = '1.3.6.1.2.1.2.2.1.10.2';
$traffic_eth0_out_oid='1.3.6.1.2.1.2.2.1.16.2';
($session,$error) = Net::SNMP->session(Hostname => "localhost",Community => "public");
die "session error: $error" unless ($session);
$result_in = $session->get_request("$traffic_eth0_in_oid ");
$result_out = $session->get_request("$traffic_eth0_out_oid ");
die "request error: ".$session->error unless (defined $result_in);
$session->close;
$traffic_in=$result_in->{"$traffic_eth0_in_oid"};
$traffic_out=$result_out->{"$traffic_eth0_out_oid"};
}
#將時間轉成 西元年月日 時:分:秒
sub get_time {
($sec,$min,$hour,$day,$mon,$year)=localtime(time);
$mon++;
if (length ($mon) == 1) {$mon = '0'.$mon;}
if (length ($day) == 1) {$day = '0'.$day;}
if (length ($hour) == 1) {$hour = '0'.$hour;}
if (length ($min) == 1) {$min = '0'.$min;}
if (length ($sec) == 1) {$sec = '0'.$sec;}
$year+=1900;
$clock="$year$mon$day $hour\\:$min\\:$sec";
}
==============================================================
最後30分鐘的圖示產出程式範例
#!/usr/bin/perl -w
use RRDs;
$log="/srv/www/perl-lib/demo.log";
$rrd="/srv/www/perl-lib/demo.rrd";
print "Open Log File\n";
open (open_file,"$log");
$start=<open_file>;
close(open_file);
$now=time;
$start_date = localtime($start);
$begin=int($now-1800);#圖示開始時間:以30分鐘以前的時間取樣(1800秒)
$endtime=int($now+1);#圖示結束時間:現在時間+1的時間取樣
$begin_date= localtime($begin);
$end_date= localtime($endtime);
print " RRD記錄初始時間為 $start_date\n";
print "圖示記錄初始時間為 $begin_date\n";
print "圖示記錄結束時間為 $end_date\n";
print "Start_time $start \n";
print "Begin_time $begin \n";
print " endtime $endtime \n";
get_time();
sleep 20;
print "Start Creating Graph \n";
RRDs::graph "/srv/www/htdocs/demo30min.png",
"--title=Demo Traffic Last Half Hour ",
"--start", $begin,
"--end", $endtime,
"--interlace",
"--imgformat","PNG",
"--width=500",
"--height=120",
"--vertical-label=bps",
"DEF:a=$rrd:a:AVERAGE",
"DEF:b=$rrd:b:AVERAGE",
"CDEF:ab=a,8,\*",
"CDEF:bb=b,8,\*",
"AREA:ab#00FF00: Traffic_In ",
"GPRINT:ab:MIN: min\\: %8.2lf %s",
"GPRINT:ab:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:ab:MAX: max\\: %8.2lf %s",
"GPRINT:ab:LAST: last\\: %8.2lf %s",
"COMMENT:\\n",
"LINE:bb#0000FF: Traffic_Out",
"GPRINT:bb:MIN: min\\: %8.2lf %s",
"GPRINT:bb:AVERAGE: avg\\: %8.2lf %s",
"GPRINT:bb:MAX: max\\: %8.2lf %s",
"GPRINT:bb:LAST: last\\: %8.2lf %s",
"COMMENT:\\n",
"COMMENT:Last Updated $clock" ,
;
if ($ERROR = RRDs::error) {
die "ERROR: $ERROR\n";
};
print "END \n";
sub get_time {
($sec,$min,$hour,$day,$mon,$year)=localtime(time);
$mon++;
if (length ($mon) == 1) {$mon = '0'.$mon;}
if (length ($day) == 1) {$day = '0'.$day;}
if (length ($hour) == 1) {$hour = '0'.$hour;}
if (length ($min) == 1) {$min = '0'.$min;}
if (length ($sec) == 1) {$sec = '0'.$sec;}
$year+=1900;
$clock="$year$mon$day $hour\\:$min\\:$sec";
}
每五分鐘執行一次即可 (30分鐘程式範列圖示如下)
=============================================
對照 cacti 程式作業分解
(1)選擇 DS(Data Source) 來源 (如某主機的網管流量)
(2)建立 rrd 資料庫
(3)更新歷史軌跡資料庫
(4)產出歷史軌跡的圖示
cacti 尚未建立 rrd 資料庫
已建立 rrd 資料庫與圖示(但還沒有DS資料)
RRA
Data Source Type
Graph Traffic
cacti [ Last Half Hour ] [DS資料來源為最後30分鐘的數據]
Perl code style V.S cacti ( Perl 山寨版圖示 與 cacti 正版圖示 對照如下 )
其它圖示範例
區間對照表
透過這一篇的介紹,大家應該可以更清楚 cacti 的設定與 rrdtool 運用的關連性了吧!
DIY 的 簡易型網管程式 已經有 MRTG 的水平吧! (哈)
再次重申,我還是會推薦大家使用 OpenSource 的網管程式.如 cacti or zabbix or opennms
Zenoss Core or Nagios
如果公司有錢的話.那就看看
HP OpenView or IBM Tivoli or Solarwinds or WhatsUp or CiscoWorks .....
OpenSource 還是有一定的極限在...廢話不過也是實話....
關於 snmpget 的技法可參考下列文章
再論 SNMP OIDs
http://xrcd2.blogspot.tw/2012/10/snmp-oid.html
利用SNMP OIDs 加入 Zabbix 監控
http://xrcd2.blogspot.tw/2012/10/snmp-oids-zabbix.html
關於網管系統的建置可參考
Cacti + XSMS_API (SOAP) (自行客製化 Cacti + SMS )
http://xrcd2.blogspot.tw/2012/05/cacti-xsmsapi-soap-cacti-sms.html
訂閱:
文章 (Atom)









































