I perform this search, where $_ can be a DN for for group or an user.
my $m = $ldap->search(
  base => "$_", 
  scope => 'base',
  filter => '(objectClass=Person)',
  attrs => ['sAMAccountName'], 
  );
if (defined($m->entry->entries->get_value('sAMAccountName'))) {
  print $m->entry->entries->get_value('sAMAccountName') . "\n";
}
This problem this is, if $_ is a group, then sAMAccountName doesn't exist, and the script fails. I am 开发者_如何学JAVAnot even sure if this works for an user =(
Does anyone know how to only print the sAMAccountName if $_ is a person?
Iterate over the search object's entries. If the attribute does not exist, it will be undef (of course), but not cause a failure because we do not attempt to dereference a method call from it.
foreach my $entry ($m->entries) {
    my ($uid, $sAMAccountName) = (
        $entry->get_value('uid'),
        $entry->get_value('sAMAccountName'),
    );
}
Because your filter is:
(objectClass=Person)
Then you will retrieve no entries when $_ is a group.
So instead of that horrible defined() call, check to see if $m->entries() is empty.
Example:
my $m = $ldap->search(
  base => "$_", 
  scope => 'base',
  filter => '(objectClass=Person)',
  attrs => ['sAMAccountName'], 
  );
my @entries = $m->entries();
if (@entries) {
  print $m->entry->entries->get_value('sAMAccountName') . "\n";
}
                                        
                                        
                                        
                                        
                                        
                                        
                                        
                                        
 加载中,请稍侯......
      
精彩评论