20130311 simple paged results with perl - plembo/onemoretech GitHub Wiki

title: simple paged results with perl link: https://onemoretech.wordpress.com/2013/03/11/simple-paged-results-with-perl/ author: phil2nc description: post_id: 4482 created: 2013/03/11 17:25:59 created_gmt: 2013/03/11 21:25:59 comment_status: closed post_name: simple-paged-results-with-perl status: publish post_type: post

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.

Copyright 2004-2019 Phil Lembo