Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Does anyone have any code that will allow a script to tail a file located on a remote system that is “not” nfs mounted?

The code below will tail a file that is NFS mounted:

open (FH,”/tmp/file); for (;;) { while (<FH>) { print “$_\n”; } FH->clearerr; }

But how do I do this on a remote file system and still use filehandles?

Code tags and other markup added by GrandFather

Replies are listed 'Best First'.
Re: How to tail file on remote host
by Corion (Patriarch) on Sep 30, 2008 at 19:55 UTC

    You simply execute the tail program remotely:

    my $remote_filename = '/somewhere/over.txt'; my $remote_host = 'rainbow'; my $cmd = "ssh $remote_host tail -f $remote_filename |"; open my $remote_tail, $cmd or die "COuldn't spawn [$cmd]: $!/$?"; while (<$remote_tail>) { print "Remote: $_"; };
      Thanks for the quick reply. This works great. How would you suggest modifying this so that I can call this in a procedure to tail the file from the last point the file was tailed. For example: tail_file($remote_server); # Do some tests - @result = tail_file($remote_server); # Now @result has just the changes caused by the test.

        Copy the whole file to your local machine and then use Algorithm::Diff or remember the last line you processed the last time and start from there.

Re: How to tail file on remote host
by salva (Canon) on Oct 01, 2008 at 08:13 UTC
    tailing through SFTP with Net::SFTP::Foreign:
    use Net::SFTP::Foreign; use Fcntl qw(SEEK_END); my $host = ...; my $file = ...; my $sftp = Net::SFTP::Foreign->new($host); $sftp->error and die "Unable to connect to remote host: ".$sftp->error +."\n"; my $fh = $sftp->open($file) or die "Unable to open file $file: ".$sftp->error."\n"; # go to end of file seek($fh, 0, SEEK_END); my $sleep = 1; while (1) { while (<$fh>) { print; $sleep = 1; } sleep $sleep; $sleep++ unless $sleep > 5; }
      Im hoping it is easy to install this in my local lib path since I don't have access to the server to install this package.
      
      Thanks for the input.  This looks pretty simple.
      
      
      -Wayne
        The only requirement is that, to handle password authentication, it needs Expect.

        If you use public/private key pairs for authentication exclusively (that's what you should be doing anyway), no additional modules are required.

        Just (recursively) copy the contents of the lib directory to the right place in your server and you are done with the installation!