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

I'm not sure where the right place here on perlmonks is to share coding examples. But.. after much flailing about i've managed to tame ssh2 {and auth and all of that} and I have a working sub that does exactly what I want and I thought I'd share. My approach to using the SSH2 connection is to send commands, poring over the output of each to decide what to do next until I"m done.
# NB: you can only do one command on a channel so we get the channel ## do the command give back the output then close the channel Note +that the command ## must be a fully "shell punctuated and escaped" sub docmd { my $chan = $ssh2->channel() or $ssh2->die_with_error ; $chan->exec("($_[0]) 2>&1") ; # my $out = ""; while (!$chan->eof) { my $buffer = ""; my $bytes = $chan->read($buffer, 100) ; $ssh2->die_with_error if $bytes < 0 ; $out .= $buffer ; } return $out ; }
and I tested it with:
print docmd("cd tmp; ls") ; print docmd("cd bin; ls") ; $ssh2->disconnect() ;

and I confess that I was amazed that it worked.

Replies are listed 'Best First'.
Re: Running commands with Net::SSH2
by haukex (Archbishop) on Aug 10, 2018 at 17:41 UTC
    I'm not sure where the right place here on perlmonks is to share coding examples.

    That would probably be Cool Uses for Perl (or sometimes Meditations). What would be great is if you turn your snippet into a runnable example (along the lines of SSCCE), that is, with the necessary use statements, and example of how to establish the connection, etc., so that it's easy to just download and run. In any case, thanks for sharing!