in reply to Correct way to use Net:SSH2 module

I use:

sub sshSendCommand { my ($self, $cmd, $pollTime) = @_; my $chan = $self->{ssh}->channel(); my $log = ''; my $timeDelta = sprintf "%4d:", time() - $self->{startTime}; $pollTime ||= 500; print "$timeDelta ssh: <$cmd> (poll time: $pollTime)\n"; $chan->exec($cmd); my @poll = {handle => $chan, events => ['in']}; while ($self->{ssh}->poll($pollTime, \@poll)) { if ($poll[0]{revents}{channel_closed}) { print "$timeDelta channel closed\n"; last; } next if !$poll[0]{revents}{in}; my $buff; $log .= $buff while $chan->read($buff, 1024); next; } print "$log\n$timeDelta ssh command complete\n"; return $log; }
True laziness is hard work

Replies are listed 'Best First'.
Re^2: Correct way to use Net:SSH2 module
by MikeKulls2 (Novice) on Mar 21, 2013 at 04:04 UTC
    OK, I can see how that works. It knows when the response has finished because the remote end disconnects. Interestingly the documentation states that your code won't work if run a second time, although it does appear to work.
      No, the documentation says you can not reuse a channel once it has been closed. But you can open several channels, even in parallel, over the same connection.

      BTW, you should also check Net::SSH::Any.

        Sorry, I misread your code, I see that you are creating a new channel for each call. The function being called channel instead of createChannel or newChannel threw me :-) With regards my original question, if I connect with shell instead of exec would I be correct in saying there is no way to tell when the end of the response has been received? Why does it not return the prompt? Also, with your code, why does a poll time of 500ms work perfectly well with a command like "ls;sleep 5;ls;"? When I reduce the poll time to 100ms it times out.