简体   繁体   English

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

[英]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. 我们没有Net :: SSH,我无法加载它。 I rolled my own using ssh keys and piping ssh. 我使用ssh键和管道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. 在这种情况下,@ ARGV是一个文本文件,其中包含IP地址,每行一个。

It works to output the rpm -qa to the screen, but I can't capture that output into the $OUT filehandle. 它可以将rpm -qa输出到屏幕,但我无法将输出捕获到$ OUT文件句柄中。 I'm just not thinking around this corner and I know I'm really close to getting it. 我只是没想到这个角落,我知道我真的很接近它。

Are you sure you need all that perl for this? 你确定你需要所有的perl吗? How about a basic for-loop? 基本的for循环怎么样? 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. 如果您在本地计算机上运行命令“ ssh $ip rpm -qa ”,输出将转到您的标准输出,您可以随意执行任何操作。

$ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM