1Net::LDAP::Examples(3)User Contributed Perl DocumentationNet::LDAP::Examples(3)
2
3
4

NAME

6       Net::LDAP::Examples - PERL LDAP by Example
7

DESCRIPTION

9       The following examples are of course PERL code, found to work with the
10       Net::LDAP modules.
11
12       The intent of this document is to give the reader a cut and paste jump
13       start to getting an LDAP application working.
14
15       Below you will find snippets of code that should work as-is with only a
16       small amount of work to correct any variable assignments and LDAP
17       specifics, e.g. Distinguished Name Syntax, related to the user's own
18       implementation.
19
20       The Standard Operating Procedure that is followed here is:
21
22       1 Package      - use Net::LDAP
23       2 Initialization    - new
24       3 Binding      - bind
25       4 Operation    - add modify moddn search
26       4.1 Processing - displaying data from a search
27       5 Error        - displaying error information
28       6 Unbinding    - unbind
29
30       Look to each of these for a snippet of code to meet your needs.
31
32       What is not covered in these examples at this time:
33
34       abandon and compare methods
35       callback subroutines
36

CODE

38   PACKAGE - Definitions
39        use Net::LDAP;
40
41   INITIALIZING
42        $ldap = Net::LDAP->new ( "yourLDAPhost.yourCompany.com" ) or die "$@";
43
44   BINDING
45        $mesg = $ldap->bind ( version => 3 );          # use for searches
46
47        $mesg = $ldap->bind ( "$userToAuthenticate",
48                              password => "$passwd",
49                              version => 3 );          # use for changes/edits
50
51        # see your LDAP administrator for information concerning the
52        # user authentication setup at your site.
53
54   OPERATION - Generating a SEARCH
55        sub LDAPsearch
56        {
57          my ($ldap,$searchString,$attrs,$base) = @_;
58
59          # if they don't pass a base... set it for them
60
61          if (!$base ) { $base = "o=mycompany, c=mycountry"; }
62
63          # if they don't pass an array of attributes...
64          # set up something for them
65
66          if (!$attrs ) { $attrs = [ 'cn','mail' ]; }
67
68          my $result = $ldap->search ( base    => "$base",
69                                       scope   => "sub",
70                                       filter  => "$searchString",
71                                       attrs   =>  $attrs
72                                     );
73
74       }
75
76        my @Attrs = ( );               # request all available attributes
77                                       # to be returned.
78
79        my $result = LDAPsearch ( $ldap, "sn=*", \@Attrs );
80
81   PROCESSING - Displaying SEARCH Results
82        #------------
83        #
84        # Accessing the data as if in a structure
85        #  i.e. Using the "as_struct"  method
86        #
87
88        my $href = $result->as_struct;
89
90        # get an array of the DN names
91
92        my @arrayOfDNs  = keys %$href;        # use DN hashes
93
94        # process each DN using it as a key
95
96        foreach ( @arrayOfDNs ) {
97          print $_, "\n";
98          my $valref = $$href{$_};
99
100          # get an array of the attribute names
101          # passed for this one DN.
102          my @arrayOfAttrs = sort keys %$valref; #use Attr hashes
103
104          my $attrName;
105          foreach $attrName (@arrayOfAttrs) {
106
107            # skip any binary data: yuck!
108            next if ( $attrName =~ /;binary$/ );
109
110            # get the attribute value (pointer) using the
111            # attribute name as the hash
112            my $attrVal =  @$valref{$attrName};
113            print "\t $attrName: @$attrVal \n";
114          }
115          print "#-------------------------------\n";
116          # End of that DN
117        }
118        #
119        #  end of as_struct method
120        #
121        #--------
122
123
124        #------------
125        #
126        # handle each of the results independently
127        # ... i.e. using the walk through method
128        #
129        my @entries = $result->entries;
130
131        my $entr;
132        foreach $entr ( @entries ) {
133          print "DN: ", $entr->dn, "\n";
134
135          my $attr;
136          foreach $attr ( sort $entr->attributes ) {
137            # skip binary we can't handle
138            next if ( $attr =~ /;binary$/ );
139            print "  $attr : ", $entr->get_value ( $attr ) ,"\n";
140          }
141
142          print "#-------------------------------\n";
143        }
144
145        #
146        # end of walk through method
147        #------------
148
149   OPERATION - Modifying entries
150        #
151        #   Modify
152        #
153        #  for each of the modifies below you'll need to supply
154        #  a full DN (Distinguished Name) for the $dn variable.
155        #   example:
156        #    cn=Jo User,ou=person,o=mycompany,c=mycountry
157        #
158        #   I would recommend doing a search (listed above)
159        #   then use the dn returned to populate the $dn variable.
160
161        #
162        #  Do we only have one result returned from the search?
163
164        if ( $result->count != 1 ) { exit; }  # Nope.. exit
165
166        my $dn = $entries[0]->dn;         # yes.. get the DN
167
168        #######################################
169        #
170        #   MODIFY using a HASH
171        #
172
173        my %ReplaceHash = ( keyword => "x", proxy => "x" );
174
175        my $result = LDAPmodifyUsingHash ( $ldap, $dn, \%ReplaceHash );
176
177        sub LDAPmodifyUsingHash
178        {
179          my ($ldap, $dn, $whatToChange ) = @_;
180          my $result = $ldap->modify ( $dn,
181                                       replace => { %$whatToChange }
182                                     );
183          return $result;
184        }
185
186        #######################################
187        #
188        #   MODIFY using a ARRAY List
189        #
190
191        my @ReplaceArrayList = [ 'keyword', "xxxxxxxxxx",
192                                 'proxy' , "yyyyyyyyyy"   ];
193
194        my $result = LDAPmodifyUsingArrayList ( $ldap, $dn, \@ReplaceArrayList );
195
196        sub LDAPmodifyUsingArrayList
197        {
198          my ($ldap, $dn, $whatToChange ) = @_;
199          my $result = $ldap->modify ( $dn,
200                                       changes => [
201                                         replace => @$whatToChange
202                                       ]
203                                     );
204          return $result;
205        }
206
207        #######################################
208        #
209        #   MODIFY using a ARRAY
210        #
211
212        my @ReplaceArray = ( 'keyword', "xxxxxxxxxx" ,
213                             'proxy' , "yyyyyyyyyy"   );
214
215        my $result = LDAPmodifyUsingArray ( $ldap, $dn, \@ReplaceArray );
216
217        sub LDAPmodifyUsingArray
218        {
219          my ($ldap, $dn, $whatToChange ) = @_;
220          my $result = $ldap->modify ( $dn,
221                                       changes => [
222                                         replace => [ @$whatToChange ]
223                                       ]
224                                     );
225          return $result;
226        }
227
228        #######################################
229        #
230        #   MODIFY an existing record using 'Changes'
231        #    (or combination of add/delete/replace)
232        #
233
234        my @whatToChange;
235        my @ReplaceArray;
236        my @DeleteArray;
237        my @AddArray;
238
239        push @AddArray, 'cn', "me myself";
240        push @ReplaceArray, 'sn', '!@#$%^&*()__+Hello There';
241        push @ReplaceArray, 'cn', "me myself I";
242        push @DeleteArray, 'cn', "me myself";
243
244        if ( $#ReplaceArray > 0 ) {
245          push @whatToChange, 'replace';
246          push @whatToChange, \@ReplaceArray;
247        }
248        if ( $#DeleteArray > 0 ) {
249          push @whatToChange, 'delete';
250          push @whatToChange, \@DeleteArray;
251        }
252        if ( $#AddArray > 0 ) {
253          push @whatToChange, 'add';
254          push @whatToChange, \@AddArray;
255        }
256
257        $result = LDAPmodify ( $ldap, $dn, \@whatToChange );
258
259        sub LDAPmodify
260        {
261          my ($ldap, $dn, $whatToChange) = @_;
262
263          my $result = $ldap->modify ( $dn,
264                                       changes => [
265                                         @$whatToChange
266                                       ]
267                                     );
268          return $result;
269        }
270
271   OPERATION - Changing the RDN
272        my $newRDN = "cn=Joseph User";
273
274        my $result = LDAPrdnChange ( $ldap, $dn, $newRDN, "archive" );
275
276
277        sub LDAPrdnChange
278        {
279          my ($ldap,$dn,$whatToChange,$action) = @_;
280
281          my $branch;
282
283          #
284          # if the archive action is selected, move this
285          # entry to another place in the directory.
286          #
287          if ( $action =~ /archive/i )  {
288            $branch = "ou=newbranch, o=mycompany, c=mycountry";
289          }
290
291          #
292          # use the 'deleteoldrdn' to keep from getting
293          # multivalues in the NAMING attribute.
294          # in most cases that would be the 'CN' attribute
295          #
296          my $result = $ldap->moddn ( $dn,
297                                      newrdn => $whatToChange,
298                                      deleteoldrdn => '1',
299                                      newsuperior => $branch
300                                    );
301
302          return $result;
303
304        }
305
306   OPERATION - Adding a new Record
307        my $DNbranch = "ou=bailiwick, o=mycompany, c=mycountry";
308
309        #
310        # check with your Directory Schema or Administrator
311        # for the correct objectClass... I'm sure it'll be different
312        #
313        my $CreateArray = [
314          objectClass => [ "top", "person", "organizationalPerson", "inetOrgPerson" ],
315          cn => "Jane User",
316          uid => "0000001",
317          sn => "User",
318          mail => "JaneUser@mycompany.com"
319        ];
320
321        #
322        # create the  new DN to look like this
323        # " cn=Jo User + uid=0000001 , ou=bailiwick, o=mycompany, c=mycountry "
324        #
325        # NOTE: this DN  MUST be changed to meet your implementation
326        #
327
328        my $NewDN = "@$CreateArray[2]=".
329                    "@$CreateArray[3]+".
330                    "@$CreateArray[4]=".
331                    "@$CreateArray[5],".
332                    $DNbranch;
333
334        LDAPentryCreate($ldap, $NewDN, $CreateArray);
335
336        #
337        # CreateArray is a reference to an anonymous array
338        # you have to dereference it in the  subroutine it's
339        # passed to.
340        #
341
342        sub LDAPentryCreate
343        {
344           my ($ldap, $dn, $whatToCreate) = @_;
345           my $result = $ldap->add ( $dn, attrs => [ @$whatToCreate ] );
346           return $result;
347        }
348
349   ERROR - Retrieving and Displaying ERROR information
350        if ( $result->code ) {
351          #
352          # if we've got an error... record it
353          #
354          LDAPerror ( "Searching", $result );
355        }
356
357        sub LDAPerror
358        {
359          my ($from, $mesg) = @_;
360          print "Return code: ", $mesg->code;
361          print "\tMessage: ", $mesg->error_name;
362          print " :",          $mesg->error_text;
363          print "MessageID: ", $mesg->mesg_id;
364          print "\tDN: ", $mesg->dn;
365
366          #---
367          # Programmer note:
368          #
369          #  "$mesg->error" DOESN'T work!!!
370          #
371          #print "\tMessage: ", $mesg->error;
372          #-----
373        }
374
375   UNBIND
376        $ldap->unbind;
377

LDAP SCHEMA RETRIEVAL

379       The following code snippet shows how to retrieve schema information.
380
381       The first procedure is to initialize a new LDAP object using the same
382       procedures as listed at the beginning of this document.
383
384       The second procedure is to bind to your directory server.  Some servers
385       may require authentication to retrieve the schema from the directory
386       server.  This procedure is listed at the beginning of this document
387       too.
388
389       After a successful bind you are ready to retrieve the schema
390       information.  You do this by initializing a schema object.
391
392        $schema = $ldap->schema ( );
393
394       In this case Net::LDAP will attempt to determine the dn under which the
395       schema can be found. First it will look for the attribute
396       "subschemaSubentry" in the root DSE. If that cannot be found then it
397       will default to the assumption of "cn=schema"
398
399       Alternatively you can specify the dn where the schema is to be found
400       with
401
402        $schema = $ldap->schema ( dn => $dn );
403
404       Once we have a dn to search for, Net::LDAP will fetch the schema entry
405       with
406
407         $mesg = $self->search ( base   => $dn,
408                                 scope  => 'base',
409                                 filter => '(objectClass=subschema)',
410                               );
411
412       Once the schema object has been initialized, schema methods are used to
413       retrieve the data.  There are a number of ways this can be done.
414       Information on the schema methods can be found in the Net::LDAP::Schema
415       pod documentation.
416
417       The following is a code snippet showing how to get and display
418       information about returned attributes.
419
420        #
421        # Get the attributes
422        #
423
424        @attributes = $schema->all_attributes ( );
425
426        #
427        # Display the attributes
428        #
429
430        foreach $ar ( @attributes ) {
431          print "attributeType: ", $ar->{name}, "\n";
432
433          #
434          # Print all the details
435          #
436
437          foreach $key ( keys %{$ar} ) {
438            print join ( "\n\t\t", "\t$key:",
439                         ref ( $ar->{$key} ) ? @{$ar->{$key}} : $ar->{$key}
440                       ), "\n";
441          }
442        }
443
444       The process is the basically the same for getting objectClass
445       information.  Where schema->all_attributes() is used, substitute
446       schema->all_objectclasses().  From that point on the process is the
447       same for both objectClasses and attributes.
448

BUGS

450       None known, but there may be some
451

AUTHOR (of this document)

453       Russell Biggs <rgb@ticnet.com>
454
456       All rights to this document are hereby relinquished to Graham Barr.
457
458
459
460perl v5.28.1                      2015-04-02            Net::LDAP::Examples(3)
Impressum