●想法
區域網路裡的資訊設備很多都有ip
想寫個小程式把ip和mac對應起來
日後如果ip或mac有更改時比較好查

●資料庫
配合access資料庫
access資料庫名稱為myoffice
table名稱為ipmac
有三個欄位,分別是im_ip, im_mac, im_name。

●用法
##用法:perl mac.pl -ip 192.168.1.1 查ip在資料庫裡對應的mac
##用法:perl mac.pl -mac 00-02-a5-87-cb-2c 查mac在資料庫裡對應的ip
##用法:perl mac.pl -arp 192.168.1.241 查電腦ip對應的mac
##用法:perl mac.pl -loop 搜尋網路上192.168.1.*的電腦比對ip及mac,無紀錄者寫入資料庫
##用法:perl mac.pl -list 列出資料庫的ip及mac資料

●程式
use strict;
use Net::Ping;
use Win32::ODBC;
use Getopt::Long;

my $myip=undef;
my $mymac=undef;
my $myarp=undef;
my $myloop=undef;
my $mylist=undef;
GetOptions ('ip=s' => \$myip, 'mac=s' => \$mymac, 'arp=s' => \$myarp, 'loop'=>\$myloop, 'list'=>\$mylist);
##用法:perl mac.pl -ip 192.168.1.1 查ip在資料庫裡對應的mac
##用法:perl mac.pl -mac 00-02-a5-87-cb-2c 查mac在資料庫裡對應的ip
##用法:perl mac.pl -arp 192.168.1.241 查電腦ip對應的mac
##用法:perl mac.pl -loop 搜尋網路上192.168.1.*的電腦比對ip及mac,無紀錄者寫入資料庫
##用法:perl mac.pl -list 列出資料庫的ip及mac資料

my $SQL='';
my $DSN='myoffice';
my $db= new Win32::ODBC($DSN);
if(!$db){
die "Could not open db to DSN because of [$!]\n";
}

my %i2m;
my %m2i;
$SQL = "SELECT * FROM ipmac";
DoSql($SQL);
while($db->FetchRow()){
my @dataRow = $db->Data();
$i2m{$dataRow[0]}=$dataRow[1];
$m2i{$dataRow[1]}=$dataRow[0];
}

if(defined($myip)){
print $myip, " ", $i2m{$myip}, " (iptable)", "\n";
}
if(defined($mymac)){
print $m2i{$mymac}, " ", $mymac, " (mactable)","\n";
}
if(defined($myarp)){
my($ip, $mac)=DoArp($myarp);
print $ip, " ", $mac, " (arp)", "\n";
}

if(defined($myloop)){
for(my $i=1; $i<=254; $i++){
my $host='192.168.1.'.$i;
next if($host eq '192.168.1.100'); #跳過自己的ip
print $host, "\n";
my($ip, $mac)=DoArp($host);
next if($mac eq '');
if(exists $i2m{$ip}){
if($i2m{$ip} ne $mac){
print $ip, " ", "Warning!!", "\n";
}else{
#print "old ==> ", $ip, " ", $mac, " ", $i2m{$ip}, "\n";
}
}else{
$SQL="INSERT INTO ipmac VALUES('$ip','$mac',' ');";
DoSql($SQL);
#print "new ==> ", $ip, " ", $mac, "\n";
}
}
}

if(defined($mylist)){
for(my $i=1; $i<=254; $i++){
my $host='192.168.1.'.$i;
my $SQL="SELECT * FROM ipmac WHERE im_ip = '$host';";
DoSql($SQL);
while($db->FetchRow()){
my @dataRow = $db->Data();
print $dataRow[0], " ", $dataRow[1], "\n";
}
}
}

sub DoArp{
my $host=shift;
my $ip='';
my $mac='';
my $p=Net::Ping->new("icmp", 1);
if($p->ping($host)){
my $str1= 'arp -a ' . $host . ' | grep ' . $host;
my $result=`$str1`;
(undef, undef, $ip, $mac, undef)=split(/\s+/, $result);
}
return $ip, $mac;
}

sub SelectAll{
my $TABLE=shift;
my $SQL = "SELECT * FROM $TABLE";
DoSql($SQL);
while($db->FetchRow()){
my @dataRow = $db->Data();
print "@dataRow \n";
}
}

sub DoSql{
my $SQL=shift;
if($db->Sql($SQL)){
print "I could not execute the following statement:\n $SQL\n";
print "$db->Error() \n";
$db->Close();
die;
}
}


arrow
arrow
    全站熱搜

    jck11 發表在 痞客邦 留言(0) 人氣()