作为运维来监控文件的状态可以扩展很多个方面,例如rsync增量备份,监控服务器是否被******等等。所以说监控文件的状态至关重要。根据这几天的工作的需求特别写了一个Perl脚本,有什么方面没有考虑到的希望大家多多指出。

需要安装的模块:

File::Monitor

File::Find::Rule

安装方法:

win下(需要有perl环境,我这里装的是activeperl)

cmd下进入c:\perl\bin

输入ppm-shell

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 & 后台运行