ScotT ScotT - 1 year ago 69
Bash Question

Perl script - print STDOUT from a piped ssh shell into a file

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>) {
  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.

Answer Source

Are you sure you need all that perl for this? How about a basic for-loop? If you run the command "ssh $ip rpm -qa" on your local machine, the output will go to your stdout and you can do whatever you like with it.

$ for ip in `cat iplist.txt`
> do
>   echo -e "${ip}\n----------------"
>   ssh $ip rpm -qa
>   echo "++++++++++++++++"
> done

or all on one line:

(for ip in `cat iplist.txt`; do echo -e "${ip}\n----------------" ; ssh $ip rpm -qa ; echo "++++++++++++++++"; done) > rpms
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download