start page | rating of books | rating of authors | reviews | copyrights

Book HomeJava and XSLTSearch this book

19.3. Adding an Entry to the Directory with Net::LDAP

Now that you've searched the directory with Net::LDAP, let's add an item. In the previous example, you bound to the directory anonymously, but when writing changes to the directory (that is, adding or deleting entries), you'll probably have to bind as an administrator or another user delegated with similar privileges. In this example, we'll use "Directory Manager" as the directory administrator.

Adding to a directory with Net::LDAP is a two-phase process:

  1. Bind to the directory as a user who has privileges to write to the directory. In this instance, we'll use "Directory Manager".

  2. Use Net::LDAP::add( ) to add the entry. add( ) takes the parts of the record that you will add to the directory as arguments.

This example, based on the following LDIF, uses add( ) to add an account for 'nvp' to the directory:

dn: uid=nvp,ou=People,o=your.domain
uid: nvp
cn: Nathan Patwardhan
givenname: Nathan
sn: Patwardhan
objectClass: person
objectClass: organizationalPerson
objectClass: account
objectClass: shadowAccount
objectClass: top
userPassword: {crypt}/-password-
loginShell: /usr/bin/bash
uidNumber: 1000
gidNumber: 1000
homeDirectory: /users/nvp

Here's the code:

my $admin = q[cn=Directory Manager];
my $ad_pw = q[adminpass];
my $lsvr  = q[ldap.my.domain];
my $org   = q[o=my.domain];
my $o_ou  = q[ou=People];
my $o_act = q[uid=nvp];

my $ldap = Net::LDAP->new($lsvr);

# Bind to a directory with DN and password
$ldap->bind($admin, password => $ad_pw);

my $l_rec = qq[$o_act, $o_ou, $org];
$result = $ldap->add($l_rec,
                   attr => [ 'cn'   => ['Nathan Patwardhan'],
                             'sn'   =>  'Patwardhan',
                             'mail' => '[email protected]',
                             'objectclass' => ['top', 'person', 'organizationalPerson', 'inetOrgPerson'],
                             'gecos' => ['Nathan Patwardhan'],
                             'loginShell' => '/usr/bin/bash',
                             'uidNumber'  => 1000,
                             'gidNumber'  => 1000,
                             'shadowPass' => 'XXXXXXXXX'
                           ]
          );

if($result->code) {
    warn "failed to add entry: @{[$result->error]}";
}

$ldap->unbind;


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.