Obtaining user information from LDAP using Perl

This is much simpler that the PHP example listed a few weeks ago. It demonstrates some of the advantages of Perl (namely, just about anything you want to do is already built as a module by someone who’s been where you are). Please refer to http://search.cpan.org for Net::LDAP and Net::LDAPS module documentation and usage examples.

In this example, we’ll bind to the LDAP server using an application account (in the cn=applications,dc=uta,dc=edu branch of our directory server) and search the account branch (cn=accounts,dc=uta,dc=edu) for all users (uid=*). We’ll fetch the NetIDs (uid), e-mail addresses (mail), and the common names (cn) for each account.

#!/usr/bin/perl -w

use strict;
use Net::LDAPS;
use Data::Dumper;

my $bind_dn       = 'cn=mavapp,cn=applications,dc=uta,dc=edu';
my $bind_password = 'mavAppPass';
my $ldaps         = Net::LDAPS->new('ldap.cedar.uta.edu');
my $mesg          = $ldaps->bind( $bind_dn, password => $bind_password );

my $result  = $ldaps->search(base => "cn=accounts,dc=uta,dc=edu",
                                            filter => "(uid=*)",
                                            attrs => ['uid','mail','cn'] );

my $entries = $result->as_struct();

# How many entries did we find?
print scalar $entries . " entries returned\n";

# Print them out
foreach my $dn ( keys %{$entries} ) {
   foreach my $attr ( keys %{$entries->{$dn}} ) {
      foreach my $val ( @{$entries->{$dn}->{$attr}} ) {
         print "$attr - $val\n";
   print "\n";

This last section could be simplified using the Data::Dumper module as:

print Dumper( $entries );


  1. Digant C Kasundra September 23, 2007 at 5:01 pm

    If you are using a modern version of OpenLDAP (probably anything 2.3 or better), you should use LDAPapi, which takes advantage of the more up-to-date api calls.


  2. Good tip. I’ve been meaning to do just that.

Leave a Reply

Your email address will not be published. Required fields are marked *