-->
为了更高效点的了解内网中mac与ip的变更情况,我写了以下脚本,在此我们可以学到如果生成彩色的输出及如果使用数组和关联数组的混合以建立复杂的数据结构。
数据文件样式:
192.168.4.99 0 00:12:3f:d2:ef:e6 WORKGROUP\6B76C16DD9D3453
我们可以使用以下命令生成原始的数据文件:
[root@supersun private]# nbtscan -m 192.168.4.0/24 |awk '{print $1"\t0\t"$3"\t"$2}' >data.mac
然后我们运行脚本,终端输出新增的IP地址及变更的数据并以红色字体打印,根据实际需要我们选择是否保存到数据文件中。
[root@supersun private]# ./scanmac.pl n
192.168.4.66 00:0b:cd:b6:8f:45 WORKGROUP\B01C804380724F0
*timeout (normal end of scan)
是否写入数据库:
y
以下是脚本的内容:
#!/usr/bin/perl -w
use strict;
use File::Copy;
use Term::ANSIColor qw(:constants);
my $red=RED;
my $rst=RESET;
my $file=shift;
my %data;
if($file){
open FD,$file;
#读取存档数据
while(<FD>){
my @arrary=split /\s+/;
$data{$arrary[0]}[$arrary[1]]{mac}=$arrary[2];
$data{$arrary[0]}[$arrary[1]]{des}=$arrary[3] if defined $arrary[3];
}
close FD;
}
#读取新产生数据并更新存档数据
open NBTSCAN,"nbtscan -m 192.168.4.0/24 |";
while(<NBTSCAN>){
next unless (/^\d/);
my ($ip,$des,$mac,$other)=split /\s+/;
if(! defined $data{$ip} ){
$data{$ip}[0]{mac}=$mac;
$data{$ip}[0]{des}=$des;
}elsif($data{$ip}[0]{mac} ne $mac){
my %tdata;
$tdata{mac}=$mac;
$tdata{des}=$des;
unshift @{$data{$ip}},\%tdata;
}else{
next;
}
print $red;
print "$ip\t$mac\t$des\n";
print $rst;
}
print "是否写入数据库:\n";
my $input=<>;
chomp $input;
if($input =~ m/[y|Y]/){
open FH,">mac.tmp";
foreach my $ip (sort keys %data){
foreach my $num (0..$#{$data{$ip}}){
print FH "$ip\t$num\t$data{$ip}[$num]{mac}\t$data{$ip}[$num]{des}\n";
}
}
close FH;
move "mac.tmp",$file;
}
模块Term::ANSIColor用于生成彩色终端
定义常量$red=red和$rst=RESET;
print $red;与$print $rst之间的输出字体为红色,具体用法我没有细看,改天闲来无事再看吧,呵呵!
另外再奉送一个小脚本,因为华为设备中要求输出的mac地址以下形式0012-3fd2-efe6,因此,以下脚本将转换上一个脚本产生数据中的mac地址。
[root@supersun macip]# cat mactun.pl
#!/usr/bin/perl -w
use strict;
my $file=shift;
open FD,$file;
while(<FD>){
my ($ip,$num,$mac,$des)=split /\s+/;
$mac =~ s/(.*):(.*):(.*):(.*):(.*):(.*)/$1$2-$3$4-$5$6/;
print "$ip\t$mac\n";
}
close FD;
[root@supersun macip]# ./mactun.pl n
192.168.4.10 0014-22d2-e9c0
192.168.4.101 000d-60cb-aa53

发表评论