clt60
clt60

Reputation: 63952

Fetch all user information with Net::LDAP

Currently have an small perl script what for the given username fetch his email address from the ActiveDirectory using Net::LDAP.

The search part is the following:

my $user = "myuser";
my $mesg = $ldap->search(
    base => "dc=some,dc=example,dc=com",
    filter => '(&(sAMAccountName=' . $user . ')(mail=*))',   #?!?
);
for my $entry ($mesg->entries) {
    my $val = $entry->get_value('mail');
    say "==$val==";
}

Working ok.

How i should modify the above statement to fetch all available information for the given user myuser? I'm looking to get an perl-ish data structure, such something like next:

my $alldata = search(... all info for the given $user ... );
say Dumper $alldata; #hashref with all stored informations for the $user

It is probably dead simple - but i'm an total AD & LDAP-dumb person...

Edit: When I dump out the $msg->entries (what is an LADP::Entry object) got something, but i'm not sure than it contains everything or only the part of the stored data...

Upvotes: 1

Views: 1660

Answers (1)

jimtut
jimtut

Reputation: 2393

I've done something similar, and I use this to query LDAP:

my $ldapResponse = $ldap->search(base => $base, filter => $filter, attrs => $attrs);

And then this to parse it:

  if ($ldapResponse && $ldapResponse->count()) {
    $ldapResponse->code && die $ldapResponse->error;
    my %domainNames = %{$ldapResponse->as_struct};
    foreach my $domainName (keys %domainNames) {
      my %ldapResponse;

      my %dnHash = %{$domainNames{$domainName}};

      foreach my $attr (sort(keys %dnHash)) {
        # Note that the value for each key of %dnHash is an array,
        # so join it together into a string.
        my $value = join(" ", @{$dnHash{$attr}});
        $ldapResponse{$attr} = $value;
      }
      // Dump/use %ldapResponse
    }
  }

I've never tried to use the ldap->entries in your code, but the above works for me!

I explicitly specify a(long) list of attributes ($attr), but perhaps that's optional as your example shows, and you can get ALL LDAP fields by just skipping that arg to search().

Upvotes: 2

Related Questions