# getMac.pl gets mac address for nic on specified machine using wmi. # written 13-jun-06 by fgb use Getopt::Long; use strict; use Win32::OLE('in'); use constant wbemFlagReturnImmediately => 0x10; use constant wbemFlagForwardOnly => 0x20; use constant USER_PRIV_ADMIN => 0x02; my $sAppName = "getMac"; my $bHelp = 0; my $sLastAddr = ""; my $sMachine = "."; my $status = 0; my $sVersion = "1.0"; my $result = GetOptions('/|-','help|?'=>\$bHelp,"machine=s"=>\$sMachine); if ($bHelp) { &help(); exit; } if ((length(@ARGV[0]) > 0) && ($sMachine eq ".")) { &help(); exit; } if (!isAdmin()) { if ($sMachine ne ".") { print "$sAppName requires admin privs; goodbye.\n"; exit; } } print "mac address for "; if ($sMachine ne ".") { print $sMachine; } else { print Win32::NodeName; } print ": "; my $oWmiService = Win32::OLE->GetObject("winmgmts:\\\\$sMachine\\root\\CIMV2") or die "WMI connection failed.\n"; my $colItems = $oWmiService->ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration", "WQL", wbemFlagReturnImmediately | wbemFlagForwardOnly); foreach my $o (in $colItems) { if ($o->{Caption} =~ /iniport/) { next; } # skip miniports if (length($o->{MACAddress}) == 0) { next; } if ($sLastAddr eq $o->{MACAddress}) { next; } # skip dups print "$o->{MACAddress}\n"; $sLastAddr = $o->{MACAddress}; } sub help { print "$sAppName $sVersion\n"; print "usage: $sAppName [-machine=]\n"; print "\nIf no machine specified, checks local machine.\n"; print "Requires admin privs.\n"; } sub isAdmin { use Win32::NetAdmin qw(UserGetAttributes); my $domain = Win32::DomainName; my $junk; my $priv; $_ = Win32::LoginName; # grab the name of the current user UserGetAttributes($domain,$_,$junk,$junk,$priv,$junk,$junk,$junk,$junk) or die "UserGetAttributes() failed: $^E"; #print "(User=$_\@$domain, privilege=$priv)\n"; return ($priv==USER_PRIV_ADMIN); } __END__