2013年2月25日 星期一

md5deep reporting to E-mail ( 使用 perl )

程式需求說明,對某一個目錄做 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月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 的資訊顯示在郵件本文中!

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 修改方式