skip to Main Content

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 => "stringn",
} );
 
sshopen2('user@hostname', $reader, $writer, $command);
 
sshopen3('user@hostname', $writer, $reader, $error, $command);

2

Answers


  1. 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;
    }
    
    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search