Reputation: 46979
In the following code I need to print output from the variables $stout
, $stderr
. How can I do this and not without using $ssh = Net::SSH::Perl->new
?
#!/usr/bin/perl
use strict;
use warnings;
use Net::SSH::Perl;
use FindBin qw($RealBin);
use File::Basename;
use lib "/nfs/site/proj/dpg/tools/lib/perl";
use Util;
use Getopt::Std;
use Net::SSH::Perl;
use Cwd;
use File::Copy;
my $host = 'someip.com.com';
my $pass = '';
my $user = '';
my $cmd = 'pwd';
my($stdout,$stderr,$exit) = system('ssh someip.com cat /nfs/site/home/aa/test11.txt') ;
if ($stdout) {
print "Standard output is \n$stdout";
} elsif($stderr) {
print "Standard error is \n$stderr";
}
Upvotes: 0
Views: 3396
Reputation: 8542
I've always been a fan of IPC::Run
:
use IPC::Run;
my $exitcode = run [ "ssh", "someip.com", "cat", ... ],
undef, \my $stdout, \my $stderr;
At this point the STDOUT
and STDERR
results from the command will be stored in those two lexicals.
Though as a solution to the general issue of ssh
'ing to a host and retrieving the contents of a file from within a Perl program, you might like IPC::PerlSSH
:
use IPC::PerlSSH;
my $ips = IPC::PerlSSH->new( Host => "someip.com" );
$ips->use_library( "FS", qw( readfile ) );
my $content = $ips->call( "readfile", "/nfs/site/home/aa/test11.txt" );
The $ips
object here will just hang around and allow for reuse to collect multiple files, execute other commands, and generally reuse the connection, rather than having to set up a new ssh
connection every time.
Upvotes: 0
Reputation: 1227
I use IO::CaptureOutput, its simpler.
use strict;
use warnings;
use IO::CaptureOutput qw(capture_exec);
my $cmd = "ssh someip.com cat /nfs/site/home/aa/test11.txt";
my ($stdout, $stderr, $success, $exitcode) = capture_exec( $cmd );
You can also use list parameters in capture_exec
which I think is safer.
Upvotes: 5
Reputation: 98108
open3 allows you to read/write all handles:
use FileHandle;
use IPC::Open3;
my $cmd = "ssh someip.com cat /nfs/site/home/aa/test11.txt";
open3(\*GPW, \*GPR, \*GPE, "$cmd") or die "$cmd";
# print GPW "write to ssh";
close GPW;
while (<GPR>) {
# read stdout
}
while (<GPE>) {
# read stderr
}
close GPR; close GPE;
Upvotes: 1