I'm in an environment where I can't load outside software. We don't have Net::SSH and I can't load it. I rolled my own using ssh keys and piping ssh. I can run any command now on the remote server without manually logging in and typing it, but I'm trying to capture the output on my own server. I'm having trouble capturing the screen output into a file because of the piped shell.
Here's the very rough generic code:
#!/usr/bin/perl -w
##
my ($ip) = @ARGV;
my $rpm_logfile = "rpms";
print "The IP file is $ip\n";
open(my $IN, "<", $ip) || die "Could not find filename $ip $!";
open(my $OUT, ">>", $rpm_logfile) || die "Could not open file $rpm_logfile $!";
while (<$IN>) {
chomp;
my $my_ip = $_;
if (not defined $my_ip) {
die "Need an IP after the command.\n";
}
# ssh key was set up, so no password needed
open my $pipe, "|-", "ssh", "$my_ip", or die "can't open pipe: $!";
# print the machine IP in the logfile
# and pretty print the output.
print $OUT "$my_ip \n***************\n";
# run the command on the other box via the ssh pipe
print {$pipe} "rpm -qa";
}; #end while INFILE
close $IN;
close $OUT;
@ARGV in this case is a text file with IP addresses in it, one per line.
It works to output the rpm -qa to the screen, but I can't capture that output into the $OUT filehandle. I'm just not thinking around this corner and I know I'm really close to getting it.
open-ed the process to write to it, so itsSTDINnow is attached to the$pipe, that you write to. So you can't get itsSTDOUT. Instead, you can do exactly the same as in the fine bash solution -- runqx(ssh $pi ...)(backticks), which returns the output.open-ing) a process which allow you to capture everything about it. There are many SO posts about that. It's just that in this case you don't need any of it since simple backticksqxdoes it. Follow the link on this docs page to a spot inperlopwhere all these are discussed.