simple paged results with perl

Way back in 2007 I published a snippet of code that showed how to use Net::LDAP::Control::Paged to search an LDAP directory that supported Simple Paged Results Control. Here’s a new variation on that theme.

Net::LDAP::LDIF is used to write the results to an LDIF file. The code is just one subroutine of a larger script used to import data from one directory to another.

Variables in play are:

@attrs is a list of attributes we want returned for each entry.
$tarHost, the directory server host name.
$dirUser, the directory user (in my case “cn=Directory Manager”).
$tarPass, the directory user password.
$tarldif, the file we’re printing search results to.

sub get_target {

  my $ldap = Net::LDAP->new($tarHost, version =>'3') or die $!;
  my $mesg = $ldap->bind($dirUsr, password =>$tarPass) or die $!;
  my $page = Net::LDAP::Control::Paged->new( size => 200 ) or die $!;

  my $ldifw = Net::LDAP::LDIF->new($tarldif, 'w') or die $!;

  my $query = "(objectclass=inetorgperson)";
  my $basedn = "ou=people,dc=example,dc=com";

  my @args = ( base =>$basedn,
			   scope =>'sub',
			   filter =>$query,
			   attrs =>@attrs,
			   control => [ $page ],
			);
  my $cookie;

  while (1) {

     $mesg = $ldap->search ( @args ) or die $!;

     while (my $entry = $mesg->shift_entry()) {
	  my $dn = $entry->dn;
	  $ldifw->write($entry);
     }
     $mesg->code and last;
     my ($resp) = $mesg->control (LDAP_CONTROL_PAGED ) or last;
     $cookie = $resp->cookie or last;
     $page->cookie( $cookie );
 }
 if ($cookie) {
     $page->cookie($cookie);
     $page->size(0);
     $ldap->search( @args );
 }
 $ldifw->done;
 $ldap->unbind;
}

Notice that I’m looping through the stack of returned entries from each “page” and then only continuing on to the next page if the search was successful (the part that begins with “$mesg->code and last”). Assuming all is well, the code then retrieves the next page. Once the stack of pages is exhausted I tell the server not to send any more (“$page->size(0)”) and then close my data file and connection to the directory server.

This entry was posted in Directory on by .

About phil

My name is Phil Lembo. In my day job I’m an enterprise IT architect for a leading distribution and services company. The rest of my time I try to maintain a semi-normal family life in the suburbs of Raleigh, NC. E-mail me at philipATlembobrothersDOTcom. The opinions expressed here are entirely my own and not those of my employers, past, present or future (except where I quote others, who will need to accept responsibility for their own rants).