利用perl監控文件狀態

做爲運維來監控文件的狀態能夠擴展不少個方面,例如rsync增量備份,監控服務器是否被******等等。因此說監控文件的狀態相當重要。根據這幾天的工做的需求特別寫了一個Perl腳本,有什麼方面沒有考慮到的但願你們多多指出。linux

須要安裝的模塊:sql

File::Monitorshell

File::Find::Rule服務器

安裝方法:運維

win下(須要有perl環境,我這裏裝的是activeperl)ide

cmd下進入c:\perl\bin測試

輸入ppm-shellspa

ppm> install File::Monitor File::Find::Rule命令行

linux下:日誌

命令行輸入cpan(若是須要配置cpan,一路回車,最後選個163鏡像就好)

cpan>install File::Monitor File::Find::Rule

 


code:

 

  
  
  
  
  1. #!/usr/bin/perl
    use strict;
    use warnings;
    use Data::Dumper;
    use File::Monitor;
    use File::Monitor::Delta;
    use File::Monitor::Object;
    use File::Find::Rule;
    use POSIX qw(strftime);
    #my @files=File::Find::Rule->not_name('.*.swp')->in('f:\mon','d:\24');  #這裏能夠寫多個目錄,我這裏作測試是用win,linux同理
    START:
    my @files=File::Find::Rule->not_name('.*.swp')->in('/home/mcshell/cu');
    my $monitor=File::Monitor->new();
    foreach my $file (@files){
        $monitor->watch({
                         name => "$file",
                         recurse => 1,              #是否遞歸目錄
  2. }
                       );
    }
  3. while(1 and sleep 3) { #每一秒檢測一次
      my @changes=$monitor->scan;
    #open FH,'>>F:\monitor_log\monitor.log' or die "$!";  #將變更的文件寫入日誌
    open FH,'>>/var/log/monitor.log' or die "$!";       #linux與win的路徑
    for my $change (@changes) {
            my $name     = $change->name;
            my @created = $change->files_created;
            my @deleted =  $change->files_deleted;
            if (@deleted){
            }
          if(@created){
            print FH "@created The created\n";   #若是有新文件則從新索引文件
      goto START;
    }
            if($change->is_mtime){  #判斷是否爲修改文件
  4.         print FH $change->name."======>";
            if ($change->is_size ) {  #若是大小變化則判斷變化多少
  5.          my $old_size = ($change->old_size)||0;
                my $new_size = ($change->new_size)||0;
                print FH "has changed size from $old_size to $new_size"."====>";
            }
            my $time = $change->new_mtime;
            if(defined $time){
            my $mtime = strftime("%Y-%m-%d %H:%M:%S\n", localtime($time));
            print FH "$mtime";
    }
            }
        }
    close FH;
    }
  6.  

測試:

win下:

F:\perl\cu>perl-monitor.pl

創建一個test.txt文件放入F:\mon,查看日誌

 

 

而後修改test.txt

 

進行遞歸目錄的建立測試。

 

 


linux測試:

#./monitor.pl & 後臺運行

 

相關文章
相關標籤/搜索