Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

developerWorks Community:

  • Close [x]

LPI exam 301 prep, Topic 302: Installation and development

Senior Level Linux Professional (LPIC-3)

Sean Walberg, Network engineer, 自由职业者
Photo of Sean Walberg
Sean Walberg has been working with Linux and UNIX since 1994 in academic, corporate, and Internet service provider environments. He has written extensively about systems administration over the past several years.

Summary:  In this tutorial, Sean Walberg helps you prepare to take the Linux Professional Institute® Senior Level Linux Professional (LPIC-3) exam. In this second in a series of six tutorials, Sean walks you through installing and configuring a Lightweight Directory Access Protocol (LDAP) server, and writing some Perl scripts to access the data. By the end of this tutorial, you'll know about LDAP server installation, configuration, and programming.

Date:  04 Dec 2007
Level:  Intermediate PDF:  A4 and Letter (392 KB | 19 pages)Get Adobe® Reader®

Activity:  19574 views
Comments:  

Developing for LDAP with Perl/C++

This section covers material for topic 302.2 for the Senior Level Linux Professional (LPIC-3) exam 301. This topic has a weight of 1.

In this section, learn how to:

  • Use Perl's Net::LDAP module
  • Write Perl scripts to bind, search, and modify directories
  • Develop in C/C++

Although OpenLDAP includes command-line clients, it's often helpful to use LDAP information in your own scripts. Perl is a popular language for scripting. Perl has a module called Net::LDAP that is used to connect to and use an LDAP server.

Getting started

Net::LDAP doesn't ship with Perl, but your distribution may include it as a package. See "Installing from packages" for more information on searching for and installing packages.

If your distribution doesn't have the Net::LDAP package, then you can download it from the Comprehensive Perl Archive Network (CPAN). As root, run perl -MCPAN -e "install Net::LDAP", which downloads and installs Net::LDAP and any dependencies.

Using Net::LDAP

Using Net::LDAP is fairly simple:

  1. Create a new Net::LDAP object.
  2. Bind to the desired server.
  3. Perform your LDAP operations.

Create a new object

In typical Perl fashion, you must create an instance of the Net::LDAP module through the new method. All further operations will be on this instance. new requires, at a minimum, the name of the server you want to connect to. For example:

my $ldap = Net::LDAP->new('localhost') or die "$@";

Here, a new Net::LDAP object is created with the new method and is passed the string localhost. The result is assigned to the $ldap variable. If the function fails, the program exits and prints an error message describing the problem. $@ is a Perl internal variable that contains the status of the last operation.

You can proceed to perform LDAP operations with the new Net::LDAP object. Each function returns a Net::LDAP::Message object that contains the status of the operation, any error messages, and any data returned from the server.

Binding to the tree

The first operation you should do is to log in or bind to the tree. Listing 6 shows a bind operation and associated error checking.


Listing 6. Perl code to bind to the tree
my $message = $ldap->bind(
	"cn=Sean Walberg,ou=people,dc=ertw,dc=com",
	password=>"test" );

if ($message->code() != 0) {
        die $message->error();
}

Listing 6 starts by calling the bind method of the previously created object. The first parameter to the function is the DN you're binding as. If you don't specify a DN, you bind anonymously. Further parameters are in the format of key=>value; the one you'll use most often is the password.

Each Net::LDAP method returns a Net::LDAP::Message object, which has the results of the function. The error code is retrieved through the code method. A code of 0 means success, so the code in Listing 6 exits the program with the error message if the result isn't 0. Note that the error is retrieved from $message->error rather than $@, like the earlier example. This is because the error isn't a Perl error; it's internal to Net::LDAP.

Once the bind is successful, you can do anything you want, subject to the server's access controls. To log out, call the unbind method.

Searching the tree

Searching is done through the search method. Like the bind method, you must pass some parameters and check the result of your query. However, the returned object now contains your data, so this must be parsed. With the search operation, the result is a Net::LDAP::Search object, which inherits all the methods from Net::LDAP::Message (such as code and error) and adds methods to help you parse the data. Listing 7 shows a search of the tree.


Listing 7. Searching the tree with search
$message = $ldap->search(base => "dc=ertw,dc=com", filter=> "(objectClass=*)");
if ($message->code() != 0) {
        print $message->error();
} else {
        foreach my $entry ($message->entries()) {
                print $entry->dn() . ": ";
                print join ", ", $entry->get_value("objectClass");
                print "\n";
        }
}

Listing 7 begins by calling the search method, passing two parameters: the base and a filter. The base tells the server where in the tree to begin searching. A complementary option, scope, tells the server how far to search:

  • base—Only the base object
  • one—Only the children of the base object (and not the base object itself)
  • sub—The base object and all its children (the default)

The filter is a string describing the objects you're interested in. You can search on attributes and perform complex AND/OR queries. objectClass=* returns any object.

The result of the search is checked, and an error is printed if a problem happened. Because the script could still recover from an error, it just prints the error and continues, rather than exiting.

The entries function returns an array of Net::LDAP::Entry objects, each with a single result. First the entry's DN is printed, and then all the object classes. If you'd rather have a text version of the whole record, the dump method prints the entire entry in text format.

Adding a new entry

You add an entry to the tree through the add method. You must pass the function the DN of the entry you wish to add, along with the attributes. The attributes are an array of key => value pairs. The value can also be an array in the case of multiple instances of the same attribute. Listing 8 shows an entry being added to the tree.


Listing 8. Adding an entry using Net::LDAP
$message  = $ldap->add(
        "cn=Fred Flintstone,ou=people,dc=ertw,dc=com",
        attr => [
                cn   => "Fred Flintstone",
                sn   => "Flintstone",
                objectclass => [ "organizationalPerson",
                        "inetOrgPerson" ],
        ]
);

if ($message->code() != 0) {
        print $message->error();
}
        

The first parameter to add is either the DN or a Net::LDAP::Entry object. If the DN is passed, you must pass an arrayref through the attr method. Even though the key => value format is used as in a hashref, Net::LDAP is expecting an arrayref, so be careful!

More about Net::LDAP

Net::LDAP provides an interface to all the LDAP functions, such as compare, delete, and moddn. They're all used similarly to the previous examples and are fully documented in the Net::LDAP manpage.

All the examples shown operate in blocking mode, which means the function returns after the response has been received from the server. You can also operate in asynchronous mode, which involves giving a callback function that is called as packets are received.

By using Net::LDAP, you can use the data stored in your LDAP tree from within your scripts. Perl is already used in a wide variety of software, so the opportunities for integration are unlimited.


Developing in C/C++

Using the C libraries is more involved than the Perl libraries. The ldap(3) manpage contains a detailed description of how to use the library, and has pointers to the other manpages describing each function. To use the LDAP C libraries, your code must first include the ldap.h include file, such as with #include <ldap.h>. Your object files must then be linked with libldap using the -lldap option to the linker.

3 of 6 | Previous | Next

Comments



static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Linux, Open source
ArticleID=273059
TutorialTitle=LPI exam 301 prep, Topic 302: Installation and development
publish-date=12042007
author1-email=sean@ertw.com
author1-email-cc=