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

Hello!
I have a problem:
I need to capture stdout and stderr from remote machines, but i want to stop capturing when time is out (timer, like alarm)
For e.g. i want to see "cat /dev/urandom" only for 10 seconds, after this time i want to kill $pid or close connection. How i can do that?
sub ssh_go{ my $host = shift;<br> my $ssh = Net::OpenSSH->new("${user}\@${host}", timeout => $ti +meout);#, async => 1) if($ssh->error != 0){... }else{ my $out = $ssh->capture({stderr_to_stdout => 1}, "$cmd +"); if($ssh->error != 0){... } $LogTable{"$host"} = $out;
Thank you!

Replies are listed 'Best First'.
Re: Net::OpenSSH how to stop(zap) capturing after time
by salva (Canon) on Mar 22, 2011 at 09:39 UTC
    Use the remote shell to kill the command after 10 seconds:
    $out = $ssh->capture({stderr_to_stdout => 1}, "$cmd & sleep 10; kill $!");

      Wow, awesome, but... If i set timeout to 1 and command to `cat /dev/urandom` it takes only 13 seconds ( "$cmd & sleep $timeout; kill \$!" )
      And if command is `echo Hello, World` script returns Exit Code 1, but i think i can fix it :)

        You could probably write a more reliable wrapper in Perl, and install it on your remote servers, or use a one-liner.

        Another option is to write your own time-limited capture method. Use pipe_out to launch the remote command and read from the returned pipe until the timeout expires. Closing the pipe will deliver a SIGPIPE to the remote process killing it.