Perl 脚本 - 将 STDOUT 从管道 ssh shell 打印到文件中

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

我处于无法加载外部软件的环境中。我们没有 Net::SSH,我无法加载它。我使用 ssh 密钥和管道 ssh 自己滚动。我现在可以 运行 远程服务器上的任何命令,而无需手动登录并输入它,但我正在尝试在我自己的服务器上捕获输出。由于管道 shell,我无法将屏幕输出捕获到文件中。

这是非常粗略的通用代码:

#!/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 在这种情况下是一个包​​含 IP 地址的文本文件,每行一个。

它可以将 rpm -qa 输出到屏幕,但我无法将该输出捕获到 $OUT 文件句柄中。我只是没有考虑这个角落,我知道我真的很接近得到它。

您确定为此需要所有的 perl 吗?一个基本的for循环怎么样?如果您 运行 在您的本地计算机上执行命令“ssh $ip rpm -qa”,输出将转到您的标准输出,您可以用它做任何您想做的事。

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

或全部在一行中:

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