【问题标题】:use perl script on remote servers and bring back output to local terminal or screen在远程服务器上使用 perl 脚本并将输出带回本地终端或屏幕
【发布时间】:2011-03-08 17:24:09
【问题描述】:

在给定输入参数的情况下,我有以下在本地工作的 perl 脚本。 我需要脚本来访问远程服务器以获取相同的信息,因为我已经成功设置了 ssh 密钥。远程服务器上日志文件的路径与本地相同。远程服务器的配置是相同的。我只需要跨多个服务器运行并将数据带回终端或文件。我需要把它放在 shell 脚本中吗?

# usage example: <this script> Jun 26 2010 <logfile>
use strict;
use warnings;
my ($mon,$day,$year) = ($ARGV[0],$ARGV[1],$ARGV[2]);
open(FH,"< $ARGV[3]") or die "can't open log file $ARGV[3]: $!\n";
while (my $line = <FH>) {
    if ($line =~ /.* $mon $day \d{2}:\d{2}:\d{2} $year:.*(ERROR:|backup-date=|host=|backup-size=|backup-time=|backup-status)/) {
    print $line;
   }
}

【问题讨论】:

    标签: perl shell unix remote-access


    【解决方案1】:

    如果您的 perl 脚本已经在远程服务器上,只需调用 ssh someserver /path/to/the.script.pl。远程 stdout 和 stderr 通过管道返回给您。

    【讨论】:

      【解决方案2】:

      您可以修改脚本以将服务器名称作为额外参数。

      # usage example: <this script> Jun 26 2010 <server> <logfile>
      use strict;
      use warnings;
      my($mon,$day,$year,$server,$file) = @ARGV;
      open(my $fh,"ssh $server cat $file |") or die "can't open log $server:$file: $!\n";
      while (my $line = <$fh>) {
          if ($line =~ /.* $mon $day \d{2}:\d{2}:\d{2} $year:.*(ERROR:|backup-date=|host=|backup-size=|backup-time=|backup-status)/) {
          print $line;
         }
      }
      

      我的版本利用了这样一个事实,即 Perl open 函数可以“打开”一个命令,并且命令的输出作为输入呈现给您的脚本。

      ----编辑

      关于您的后续问题,如果该文件存在于多个主机上的同一位置,那么您可以交换参数顺序并在命令行上传递主机列表:

      # usage example: <this script> Jun 26 2010 <logfile> <server> ...
      use strict;
      use warnings;
      my($mon,$day,$year,$file) = @ARGV;
      splice(@ARGV, 0, 4, ());            # Discard first 4 args
      foreach my $server ( @ARGV ) {
          open(my $fh,"ssh $server cat $file |") or die "can't open log $server:$file: $!\n";
          while (my $line = <$fh>) {
              if ($line =~ /.* $mon $day \d{2}:\d{2}:\d{2} $year:.*(ERROR:|backup-date=|host=|backup-size=|backup-time=|backup-status)/) {
                  print $line;
              }
          }
          close($fh);
      }
      

      【讨论】:

      • 感谢格兰特。我对此进行了测试。这很好用!比如说,我有一个主机列表,例如 host1、host2、host3。什么是一次通过所有这些的干净方法? hostnames.txt: 主机 1 主机 2 主机 3
      猜你喜欢
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 2018-01-15
      • 1970-01-01
      • 2013-12-28
      相关资源
      最近更新 更多