Working with Net::LDAP::LDIF

The search.pl script provided a simple introduction to retrieving data from an LDAP directory. However, the query results represented the state of the directory at a single point in time. The script has no good way to save the search results, and the way in which it prints the information is useful for humans, but not useful to any other LDAP tools. You need the ability to save the results in a format that can be parsed by other LDAP tools: in other words, you need to be able to read and write LDIF files directly from Perl code.

The Net::LDAP::LDIF module provides the ability to work with LDIF files. To introduce Net::LDAP::LDIF, we’ll revisit search.pl and replace the call to dump( ) with code to produce valid LDIF output. Your first modification to the script is to add a second use pragma that imports the LDIF module:

use Net::LDAP::LDIF;

Next, the script must create a new instance of a Net::LDAP::LDIF object. Output from this object can be linked to an existing file handle such as STDOUT, as shown here:

$ldif = Net::LDAP::LDIF->new (scalar <STDOUT>, "w")
     or die $!;

It is possible to pass a filename to the new( ) method, as well as inform the module how this file will be used (”r" for read, "w" for write + truncate, and "a" for write + append). This line of code creates an LDIF output stream named result.ldif in the current directory:

$ldif = Net::LDAP::LDIF->new ("./result.ldif", "w")
     or die $!;

It is best to use this code after you’ve run the search ...

Get LDAP System Administration now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.