【发布时间】: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