【发布时间】:2011-02-22 05:06:43
【问题描述】:
这是我想要达到的目标。
我有一个 perl 脚本,它查看一组直接解析它找到的文件并定位特定字符串。如果找到特定字符串,则忽略它,如果找到字符串的第一部分,但第二部分不匹配,则将其写入日志文件。
我坚持的部分是如何读取整个文件,并查看字符串是否存在于整个文件中。
一些背景知识,我正在尝试编写一个脚本来读取 cisco rancid 文件,并查找 sys 日志记录详细信息。这些都存储在配置中
记录 x.x.x.x
其中 x.x.x.x 是系统日志 IP 地址。
目前,我可以读取文件,逐行检查,看看文件是否包含日志记录 x.x.x.x,如果有,则忽略它。
如果它包含日志记录 y.y.y.y(其中 y 是与应有的不同的 IP),它将写入日志文件,表明日志记录已设置,但配置不正确。但是我一辈子都想不出如何让它读取整个文件,如果不存在记录 x.x.x.x 甚至记录 y.y.y.y 来写出它没有配置。
脚本在下面
#!/usr/bin/perl
use strict;
use warnings;
#Syslog Checker.... V0.0.1
##Config Items
my $basedir = "/home/srelf/Documents/Projects/perl/Configs";
my @verdir = qw(sw_a);
my $fulldir;
my $configs;
my $loghost = "x.x.x.x";
my $combidir;
use POSIX qw(strftime);
$now_string = strftime "%a%b%e%Y", gmtime;
open FILE, ">>Configchecker.$now_string.txt" or die $!;
print FILE "### Logging Host Settings ###\n";
close FILE;
foreach $combidir (@verdir) {
$fulldir = "$basedir/$combidir";
opendir( DIR, $fulldir );
my @files = grep { $_ ne '.' && $_ ne '..' } readdir DIR;
closedir(DIR);
while ( @files > 0 ) {
$configs = pop @files;
# print "$fulldir/$configs\n"; # used for debug shows current file with full path.
open FH, "$fulldir/$configs" or die $!;
@dataarry = <FH>;
foreach my $line (@dataarry) {
# Start an if statement, the condition of which is
# "If this particular line contains logging + IP address."
if ( $line =~ m/logging \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/i ) {
#then if the line located above contains logging and the log host ignore it
if ( $line =~ m/logging $loghost/i ) {
}
# if the above line contains an ip but it is not the correct ip do the below.
elsif ( $line =~
m/logging \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/i )
{
open FILE, ">>Configchecker.$now_string.txt" or die $!;
print FILE "$configs\n";
print FILE
"Logging for this device is set, but pointing at the wrong host: $line\n";
close FILE;
} # End the if condition here.
}
}
} # End the foreach loop here;
open FILE, ">>Configchecker.$now_string.txt" or die $!;
print FILE "### NTP Settings Check ###\n";
close FILE;
}
提前感谢您的帮助。
我对 perl 很陌生,这是我的第一次尝试。 史蒂夫。
【问题讨论】: