Perl & LDAP

This month's perl article will cover the basics of using the Perl Net::LDAP module to access a LDAP server, from searching the directory tree to adding and deleting entries.

The first thing you need to know about Net::LDAP is how to bind to a LDAP tree. First you create a Net::LDAP object, then call the bind method, as follows:

my($ldap) = Net::LDAP->new('') or die "Can't bind to ldap: $!\n";

            dn       => "cn=Manager,dc=domain,dc=com",
            password => "s3cr3t",

Possibly the most useful thing you can do in LDAP is searching the directory, and using Perl makes it easy. This is done by calling the search method, and passing it the base and search filters. We also check the result for any errors that may have occurred.

my($mesg) = $ldap->search( base   => "dc=domain,dc=com",
                           filter => '(userid=root)');

$mesg->code && die $mesg->error;

Now its a simple matter of looping though all the entries returned, and manipulating them further, if required. Our example will simply print out any matching attributes.

foreach $entry ($mesg->all_entries) { $entry->dump; }
   # OR
map { $_->dump } $mesg->all_entries;

To add an entry to the field, we simply bind to the tree as before, not forgetting to check for errors.

$result = $ldap->add( dn => "cn=test,ou=Group,dc=domain,dc=com",
                        attr => [ 'cn'  => 'Test User',
                                  'sn'  => 'User',
                                  'uid' => 'test',

$result->code && warn "failed to add entry: ", $result->error;

Deleting an entry is almost as simple. You simply call the delete function, with the distinguished name of the entry you want to delete.

$ldap->delete( "cn=test,ou=Group,dc=domain,dc=com" );

To modify individual attributes, you simply use the modify function, passing it the attributes you wish to delete or replace.

$ldap->modify( $dn,
   changes => [
      add     => [ sn => 'User' ],                    # Add sn=User
      delete  => [ faxNumber => []],                  # Delete all fax numbers
      delete  => [ telephoneNumber => ['911']],       # delete phone number 911
      replace => [ email => 'test\']    # change email address

So, as you can see, you can easily manipulate LDAP entries using perl with Net::LDAP. For more information on this module, see Net::LDAP(1pm).