http://qs321.pair.com?node_id=1076629

glenn has asked for the wisdom of the Perl Monks concerning the following question:

I know this is related to AD and LDAP more so than perl problem of processing the data but I hope someone can help.

I am adding a check against our AD that a user is allowed to create licenses for our products. That user will be added to a group so I need to get the list of groups the user is part of. However; I only have the domain username work work from and cannot figure out how to get the CN of the user from the samaccountname.

$|=1; use Net::LDAP; use Data::Dumper; $^W++; # Turn on warnings my @DCs; my @unit; my $NS = qx"nslookup -type=srv _ldap._tcp.dc._msdcs.us.megatrends.com" +; foreach my $line (split("\n",$NS)) { if ($line =~ m/priority\s+=\s+(\d+)/) { $unit[0] = $1; } if ($line =~ m/weight\s+=\s+(\d+)/) { $unit[1] = $1; } if ($line =~ m/port\s+=\s+(\d+)/) { $unit[2] = $1; } if ($line =~ m/svr hostname\s+=\s+(.+)/) { $unit[3] = $1; my $index = 0; if (@DCs > 0) { if ($unit[1] < $DCs[0][1]) { #use nearest AD first unshift(@DCs, [@unit]); } elsif ($unit[0] < $DCs[0][0] and $unit[1] <= $DCs[0][1]) + { #use preferred only if it is the same distance or clos +er unshift(@DCs, [@unit]); } else { push(@DCs, [@unit]); } } else { push(@DCs, [@unit]); } @unit = (); } } my $result = "failed"; my $ldap = undef; for (my $d = 0; $d < @DCs; $d++) { $ldap = Net::LDAP->new($DCs[$d][3], port=>$DCs[$d][2]) or print "$ +@"; if (defined $ldap) { print "Connected to [$DCs[$d][3]] on port [$DCs[$d][2]]\n"; my $user = "megatrends.com\\glennt"; my $username = ""; if ($user =~ m/.+\\(.+)/) { $username = $1; } elsif ($user =~ m/(.+)\@.+/) { $username = $1; } my $password = "*******************"; my $mesg = $ldap->bind($user, password=>$password); if ($mesg->code) { #bind > 0 is error. if ($mesg->code == 1) { die "Bad credinicals\n"; } else { die "Bind code: ". $mesg->code ." error: ". $mesg->err +or ."\n"; } } else { print "successfully authenticated\n"; $search = $ldap->search(base=>"cn=Users,dc=us,dc=megatrend +s,dc=com",scope=>"subtree",filter=>"(sAMAccountName=$username)",attrs +=>['memberOf'],sizelimit=>1); my $userstate = "Non-Valid user"; foreach my $group ($search->entry(0)->get_value('memberOf' +)) { #print "Entry: $group\n"; if ($group =~ m/StorTrends-License Generator/) { $userstate = "Valid user"; $result = "success"; last; } } print "User is: $userstate\n"; } $mesg = $ldap->unbind; } elsif ($d eq @DCs) { print "Failed to connect\n"; } if ($result eq "success") { last; } }