【问题标题】:Perl script - print STDOUT from a piped ssh shell into a filePerl 脚本 - 将 STDOUT 从管道 ssh shell 打印到文件中
【发布时间】:2017-01-23 00:06:59
【问题描述】:

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

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

#!/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,你 open-ed 进程来写入它,所以它的 STDIN 现在附加到你写入的 $pipe .所以你不能得到它的STDOUT。相反,您可以执行与精细 bash 解决方案完全相同的操作 - 运行 qx(ssh $pi ...)(反引号),它会返回输出。
  • 是的,没错。 open 是一个单向过程——要么写要么读,但不能两者兼而有之。我在回旋中尝试的其中一件事是 qq(ssh $ip...),但 qq 是双引号而不是反引号。如果我只是换了一封信,我就会得到它。或者只是在命令周围放置反引号。
  • 正确。请注意,尽管有多种方法可以运行(或open-ing)进程,让您可以捕获有关它的所有内容。有很多关于这个的帖子。只是在这种情况下,您不需要任何它,因为简单的反引号 qx 就可以了。按照此文档页面上的链接到 perlop 中讨论所有这些的位置。

标签: perl shell ssh pipe stdout


【解决方案1】:

你确定你需要所有的 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

【讨论】:

  • 有时,在深夜,我们会有这些“哦,呃”的时刻。这是其中之一。这样可行。我会从这里开始。谢谢!
  • 很高兴能提供帮助,我自己也有很多这样的时刻。当 stackoverflow 帮助我解决了我自己的问题时,我喜欢尝试回答一个问题,而今天已经有几个问题了 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 2012-02-25
  • 2014-03-31
相关资源
最近更新 更多