Searching an LDAP Directory with Net::LDAP
One of the most common actions you’ll perform against LDAP is searching. If you’re using LDAP as a repository for your mail aliases, you’ll search the directory each time mail is sent to a given address. If you’re using LDAP as a repository for user accounts, you’ll search the directory every time a user logs into your system, or when a user performs a task on the system that requires information that resides only in LDAP.
Under LDAP, searching consists of three parts:
Binding to a directory server by name (or by other credentials, such as Kerberos tokens) and port. You can provide a login and password for the authentication or bind anonymously if you have permissions to search or write a part of the directory.
Passing your search request to the directory server.
Unbinding from the directory server, thus closing the connection.
Let’s say that you want to find a user called nvp in the directory server that’s living on
ldap.your.server. With Net::LDAP, do the
following:
use Net::LDAP;
my $lsvr = 'ldap.your.domain';
my $ldap = Net::LDAP->new($lsvr)
or die "error connecting to $lsvr: $@";
$ldap->bind; # Bind anonymously, that is, no login and pass
my $results = $ldap->search ( # Perform a search for 'nvp'
filter => "(&(uid=nvp) (o=your.domain))"
);
if($results->code) {
die "received LDAP error: @{[$results->error]};
}
foreach my $entry ($results->all_entries) {
$entry->dump;
}
$ldap->unbind; # Unbind and close connectionBecome an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access