How to capture command output in perl using Net::SSH?

81 views Asked by At

I've found lots of ways to use similar Perl ssh modules to capture ssh command line output (e.g. Net::SSH::Perl) but not how to do this with Net::Perl, which is what I want because it is packaged in Debian.

I found an example which shows some usage of Net::Perl but not enough for this novice to run ls -1 on a remote system and send the output to my console, but I want to capture the output in a @list:

use Net::SSH qw(ssh issh sshopen2 sshopen3);
 
ssh('user@hostname', $command);
 
issh('user@hostname', $command);
 
ssh_cmd('user@hostname', $command);
ssh_cmd( {
  user => 'user',
  host => 'host.name',
  command => 'command',
  args => [ '-arg1', '-arg2' ],
  stdin_string => "string\n",
} );
 
sshopen2('user@hostname', $reader, $writer, $command);
 
sshopen3('user@hostname', $writer, $reader, $error, $command);
2

There are 2 answers

0
ikegami On

Since you didn't say anything about being interactive, all you need is

use IPC::System::Simple qw( capturex );

my @lines = capturex( ssh => $user_host, $remote_cmd );

Or if you want to capture both STDOUT and STDERR,

use IPC::Run qw( run );

run [ ssh => $user_host, $remote_cmd ],
   ">",  \my $stdout,
   "2>", \my $stderr;

my @lines = split /^/m, $stdout;
6
amphetamachine On

The $reader and $writer arguments refer to file handles.

Here's an example of using a simple in-memory file handle to save the contents of the command output:

use Net::SSH qw/ sshopen3 /;

open my $memory_handle, '>', \my $var
    or die "Can't open memory file: $!";

my $command = 'ls -l';

sshopen3('user@hostname', undef, $memory_handle, my $error, $command);

while (my $output_line = <$memory_handle>) {
    print $output_line;
}