如何使用perl脚本使用bash管道

时间:2018-06-07 16:11:01

标签: linux perl

我需要使用perl脚本使用system运行此命令。此代码行不起作用。你知道为什么

system("ping -w 300  -i $interval $host \|  sed 's/\(.*\)/\$(date +%F\ %T) \1/g' >> $ test" )

2 个答案:

答案 0 :(得分:1)

您的程序充斥着代码注入错误。

使用localtime作为时间戳而不包括时区信息(例如,与UTC的偏移量)在夏令时的地方是有问题的。

这是解决这些问题的解决方案:

use POSIX              qw( strftime );
use String::ShellQuote qw( shell_quote );

open(my $fh_log, '>>', $test)
   or die $!;

open(my $pipe, '|-', "ping", "-w", "300", "-i", $interval, "--", $host)
   or die $!;

while (<$pipe>) {
   my $ts = strftime("%Y-%m-%dT%H:%M:%S%z", localtime);
   print($fh_log "[$ts] $_");
}

答案 1 :(得分:-1)

my $ping_check =`ping -w 300  -i $interval $host | while read line; do echo \`date \+%F%T\` - \$line >> $logfile; done `;

使用此代码行,我能够得到我需要的东西