in reply to tf - tail a file and output separator line when inactive

Often I find myself doing tail -f file | grep --line-buffered "kernel" and your program has given me the inspiration to automate that. This is my version. It features taint mode and File::Tail:

#!/usr/bin/perl -T use strict; use warnings; use File::Tail; die "Not enough arguments\n" unless @ARGV; my ($file, $regex) = @ARGV; $regex = '.' unless defined $regex && length $regex; my $tail = File::Tail->new ( name => $file, maxinterval => 5, adjustafter => 10, ); $SIG{ALRM} = sub { printf "\n%s\n", '='x80; }; while (defined ($_ = $tail->read)) { print && alarm 2 if /$regex/; }

Let me anticipate that someone is going to reply talking about code interpolation in the regex:

# ~/bin/tf2.pl file '(??{print "Hello, world!\n"})' Eval-group not allowed at runtime, use re 'eval' in regex m/(??{print +"Hello, world!\n"})/ at /root/bin/tf2.pl line 20.

Update: Minor change according to imp's comment.

--
David Serrano

Replies are listed 'Best First'.
Re^2: tf - tail a file and output separator line when inactive
by imp (Priest) on Jul 18, 2006 at 17:46 UTC
    Nice addition.

    I would only change one thing:

    while (defined ($_ = $tail->read)) { if (/$regex/) { print; alarm 2; } }

    That will prevent separator lines after reading a line that was filtered.

Re^2: tf - tail a file and output separator line when inactive
by ikegami (Patriarch) on Jul 18, 2006 at 17:09 UTC
    use re 'eval'; would remove the error, but using it would defy taint checking.

      My point is precisely that there's no way of running arbitrary code even when the regex isn't being checked or cleaned. Of course, the user running this will often be root so this is only an issue if the script is somehow made setuid. I only pointed it out to avoid the typical subthread about "Your usage of /$regex/ is insecure!".

      --
      David Serrano

        Sorry, I had misunderstood. Had I understood your point, I would have said:

        Indeed, without use re 'eval';, regexps won't knowingly run Perl code in interpolated variables. However, it's still possible to write very expensive regepxs and (I think) to crash Perl. I don't know if a crash can be exploited to execute native code.

      using it would defy taint checking.

      You mean “defeat” – unless you want to say that the code will doggedly refuse to be taint-checked. :-)

      Makeshifts last the longest.