perl 如何将打印输出发送到文件

r3i60tvu  于 2023-06-23  发布在  Perl
关注(0)|答案(1)|浏览(168)

我正试图发送成功拉IPS的打印声明,但没有拉。但我想不出来任何帮助都将不胜感激

#!/usr/bin/perl
use strict;
use warnings;

my $ip;
my $gw;
my $host;
my $cmd;
my $fetch;
my $cmd1;
my $cmd2;
my @grep=();
my @cmdout=();
my $date=`/bin/date "+%b %d %Y"`;
my $filename = '/var/log/scripts/ips_output.txt';

chomp $ver;
my $pathcmd = "/opt/CPshrd-$ver/bin/cprid_util";
my @arr=();

file(my $line=<FH>)
{
if ($line !~ /^#/) {
push(@arr,$line);
        }
}

foreach my $arrVal (@arr){
$ip=(split /,/,$arrVal)[1];
$gw=(split /,/,$arrVal)[0];
chomp $ip;
chomp $gw;
$cmd = "$pathcmd -server $ip -verbose rexec -rcmd  bash -c \"fw amw fetch -f\"";
$fetch = "$pathcmd -server $ip -verbose rexec -rcmd  bash -c \"fw stat -b AMW\"";

$cmd1 = `$cmd`;
$cmd2 = `$fetch`;
@cmdout = ($cmd1);

my $push = " policy succeeded";
 if  ( grep ( /$push/, @cmdout) ) {
print "$gw,Successful pull IPS, $date";
}else {
print "$gw, Did not pull IPS\n";
}
open(FILE, '>>',$filename);
        print FILE @cmdout;
close(FILE);
}

打印输出是我想发送到文件的结果,但不知道为什么我不能这样做。

lqfhib0f

lqfhib0f1#

您需要添加一些检查和警告来调试代码。如果@arr为空,则不会打印任何内容。在open中添加一个骰子,这样如果你没有权限,你会得到一个有意义的错误,并在数组中循环:

use strict;
use warnings;

my $ip;
my $gw;
my $host;
my $cmd;
my $fetch;
my $cmd1;
my $cmd2;
my @grep;
my @cmdou;
my $date=`/bin/date "+%b %d %Y"`;
my $filename = '/tmp/output.txt';

#chomp $ver; #whats this?

my $pathcmd = "dmesg"; #changed for testing
my @arr;


# Comment out this, what is it for?
# file(my $line=<FH>) {
#     if ($line !~ /^#/) {
#         push(@arr,$line);
#     }
# }

# TESTING make sure there is one element in array:
push @arr, 1;
my $ok;

foreach my $arrVal (@arr){
    $ok = 1;
    $ip=(split /,/,$arrVal)[1];
    $gw=(split /,/,$arrVal)[0];
    chomp $ip;
    chomp $gw;
    #$cmd = "$pathcmd -server $ip -verbose rexec -rcmd  bash -c \"fw amw fetch -f\"";
    #$fetch = "$pathcmd -server $ip -verbose rexec -rcmd  bash -c \"fw stat -b AMW\"";

    $cmd = "$pathcmd";
    $fetch = "$pathcmd";

    $cmd1 = `$cmd`;
    $cmd2 = `$fetch`;
    my @cmdout = ($cmd1);

    my $push = " policy succeeded";
    if  ( grep ( /$push/, @cmdout) ) {
    print "$gw,Successful pull IPS, $date";
    }else {
    print "$gw, Did not pull IPS\n";
    }

    open(my $fh, ">>:encoding(UTF-8)", "$filename" ) or die("can't open $filename"); #add error message here
    print $fh  "Beginning of output\n";
    foreach my $i ( @cmdout ) { #loop thru array
        print $fh $i;
    }
    close($fh);

}

if (not $ok) {print "Warning \@arr was empty\n"} #add warning message here

相关问题