这是我想要实现的目标。
我有一个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的新手,这是我的第一枪。 史蒂夫。
答案 0 :(得分:2)
foreach my $configs (@files)
{
my $CONFIGURED=0;
open FH, "$fulldir/$configs" or die $!;
while (<FH>)
{
if ($_ =~ m/logging/)
{
$CONFIGURED++;
}
if ($_ =~ m/logging \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/i and $_ !~ m/logging $loghost/i)
{
print "Logging for this device is set, but pointing at the wrong host: $_\n";
}
}
if ($CONFIGURED == 0)
{
print "NOT CONFIGURED $configs\n";
}
}