开发者

How to read multiple files from the same directory using File::Tail?

开发者 https://www.devze.com 2023-02-18 22:37 出处:网络
I am writing a program to read the rules and logs file from a IDS system. I am using File::Tail function inside Perl

I am writing a program to read the rules and logs file from a IDS system. I am using File::Tail function inside Perl Cannot figure out how to use it. Here are some of my examples...

Example 1

#!/usr/local/bin/perl
use Fail::tail;

opendir RUL, "/etc/snort/rules" || die "Could not open RUL directory\n $!";

my @allrule = grep {/.rules$/} readdir RUL;
close RUL;

   foreach my $rulefile (@allrule)
   {
      open(LF, "/etc/snort/rules/$rulefile") or die "$!";
      while(<LF>)

       print "$\n";
   }

with this example I am able to print all the rules on my terminal... How to change the rules using file::tail function and even write all the rules to a new file?

I tried this:

Example 2
#!/user/local/bin/perl
.
.
.
foreach my $rulefile(@allfule)
{
   $file = File::Tail->new("/etc/snort/rules/$rulefile");
   while (defined(my $line = $file -> read))
   {
       print $line;开发者_运维技巧
   }
}

Example 2 would not run. Anyone have any ideas as to why it does not run ?


I have not worked with File::Tail, but based on its CPAN documentation and the behavior you are seeing it looks like once you start it tailing that first file in your array, it stays there waiting until you stop tailing that file.

Have a look at the usage of select with File::Tail from CPAN.

It looks like you basically need to use File::Tail::select and pass an array of File::Tail objects to it along with whatever other basic logic you need, of course, such as the loop shown in the example, etc.


Writing it to a file:

open(my $outfile, ">/path/to/someoutfile") or die $!; # use >> if you want to append instead of overwrite
foreach my $rulefile(@allfule)
{
   $file = File::Tail->new("/etc/snort/rules/$rulefile");
   while (defined(my $line = $file->read))
   {
       print $outfile $line;
   }
}
close($outfile);

Hopefully helps you with your immediate problem. I have a feeling there's a better way to do it but I'm not sure exactly what you're trying to accomplish. For the logs Fail::Tail makes sense, but (i'm assuming) the rule files are static so Fail::Tail seems unnecessary.


I'm guessing that you mean File::Tail? (I can't find a Fail::Tail on CPAN).

The documentation at File::Tail says:

read

read returns one line from the input file. If there are no lines ready, it blocks until there are.

So your loop will never reliably complete. I have never looked at File::Tail before, but I think you need to take note of where it says

nowait

Does not block on read, but returns an empty string if there is nothing to read. DO NOT USE THIS unless you know what you are doing. If you are using it in a loop, you probably DON'T know what you are doing. If you want to read tails from multiple files, use select.

0

精彩评论

暂无评论...
验证码 换一张
取 消