Net::LD...Examples(3)
π NAME π
okay bestie, this is the manual page for Net::LD...Examples(3) β User Contributed Perl Documentation β and the module is Net::LDAP::Examples, aka PERL LDAP by Example. Weβre keeping every single detail because facts are sacred and vibes are extra. π
π DESCRIPTION π
The examples below are, of course, PERL code thatβs been found to work with the Net::LDAP modules. β¨
The whole point of this doc is to give you a cute little cut-and-paste jump start so you can actually get an LDAP application working. No cap.
Below youβll find snippets of code that should work as-is with only a small amount of work to correct any variable assignments and LDAP specifics β like Distinguished Name Syntax β related to your own implementation. π«Ά
The Standard Operating Procedure thatβs followed here is:
- Package β
use Net::LDAP - Initialization β
new - Binding β
bind - Operation β
add modify moddn search4.1 Processing β displaying data from a search - Error β displaying error information
- Unbinding β
unbind
Look to each of these for a snippet of code to meet your needs. π
What is not covered in these examples at this time:
abandonandcomparemethods- callback subroutines
β¨ CODE β¨
π¦ PACKAGE - Definitions
First things first, bestie: pull in the module.
use Net::LDAP;
π§ INITIALIZING
Make your connection object. This is the main character moment.
$ldap = Net::LDAP->new ( "yourLDAPhost.yourCompany.com" ) or die "$@";
π BINDING
Bind for searches:
$mesg = $ldap->bind ( version => 3 ); # use for searches
$mesg = $ldap->bind ( "$userToAuthenticate",
password => "$passwd",
version => 3 ); # use for changes/edits
# see your LDAP administrator for information concerning the
# user authentication setup at your site.
Like, genuinely check with your LDAP administrator about the user authentication setup at your site. That part is not a vibe, itβs important. π«Ά
π OPERATION - Generating a SEARCH
This sub is iconic. If no base is passed, it sets one for you. If no array of attributes is passed, it sets up something for you. Then it runs the search.
sub LDAPsearch
{
my ($ldap,$searchString,$attrs,$base) = @_;
# if they don't pass a base... set it for them
if (!$base ) { $base = "o=mycompany, c=mycountry"; }
# if they don't pass an array of attributes...
# set up something for them
if (!$attrs ) { $attrs = [ 'cn','mail' ]; }
my $result = $ldap->search ( base => "$base",
scope => "sub",
filter => "$searchString",
attrs => $attrs
);
}
my @Attrs = ( ); # request all available attributes
# to be returned.
my $result = LDAPsearch ( $ldap, "sn=*", \@Attrs );
The example requests all available attributes to be returned by passing the empty @Attrs and the filter "sn=*". Slay. β¨
π§Ό PROCESSING - Displaying SEARCH Results
Two ways to process the results, bestie. First up: accessing the data as if itβs in a structure β i.e. using the as_struct method.
#------------
#
# Accessing the data as if in a structure
# i.e. Using the "as_struct" method
#
my $href = $result->as_struct;
# get an array of the DN names
my @arrayOfDNs = keys %$href; # use DN hashes
# process each DN using it as a key
foreach ( @arrayOfDNs ) {
print $_, "\n";
my $valref = $$href{$_};
# get an array of the attribute names
# passed for this one DN.
my @arrayOfAttrs = sort keys %$valref; #use Attr hashes
my $attrName;
foreach $attrName (@arrayOfAttrs) {
# skip any binary data: yuck!
next if ( $attrName =~ /;binary$/ );
# get the attribute value (pointer) using the
# attribute name as the hash
my $attrVal = @$valref{$attrName};
print "\t $attrName: @$attrVal \n";
}
print "#-------------------------------\n";
# End of that DN
}
#
# end of as_struct method
#
#--------
Then thereβs handling each of the results independently β i.e. using the walk through method.
#------------
#
# handle each of the results independently
# ... i.e. using the walk through method
#
my @entries = $result->entries;
my $entr;
foreach $entr ( @entries ) {
print "DN: ", $entr->dn, "\n";
my $attr;
foreach $attr ( sort $entr->attributes ) {
# skip binary we can't handle
next if ( $attr =~ /;binary$/ );
print " $attr : ", $entr->get_value ( $attr ) ,"\n";
}
print "#-------------------------------\n";
}
#
# end of walk through method
#------------
Both of these skip the ;binary attributes because, as the code says: yuck. π
π οΈ OPERATION - Modifying entries
For each of the modifies below, youβll need to supply a full DN (Distinguished Name) for the $dn variable. Example:
cn=Jo User,ou=person,o=mycompany,c=mycountry
The doc recommends doing a search (listed above), then using the dn returned to populate the $dn variable. Also, check whether you only have one result returned from the search β if not, exit.
#
# Modify
#
# for each of the modifies below you'll need to supply
# a full DN (Distinguished Name) for the $dn variable.
# example:
# cn=Jo User,ou=person,o=mycompany,c=mycountry
#
# I would recommend doing a search (listed above)
# then use the dn returned to populate the $dn variable.
#
# Do we only have one result returned from the search?
if ( $result->count != 1 ) { exit; } # Nope.. exit
my $dn = $entries[0]->dn; # yes.. get the DN
#######################################
#
# MODIFY using a HASH
#
my %ReplaceHash = ( keyword => "x", proxy => "x" );
my $result = LDAPmodifyUsingHash ( $ldap, $dn, \%ReplaceHash );
sub LDAPmodifyUsingHash
{
my ($ldap, $dn, $whatToChange ) = @_;
my $result = $ldap->modify ( $dn,
replace => { %$whatToChange }
);
return $result;
}
#######################################
#
# MODIFY using a ARRAY List
#
my @ReplaceArrayList = [ 'keyword', "xxxxxxxxxx",
'proxy' , "yyyyyyyyyy" ];
my $result = LDAPmodifyUsingArrayList ( $ldap, $dn, \@ReplaceArrayList );
sub LDAPmodifyUsingArrayList
{
my ($ldap, $dn, $whatToChange ) = @_;
my $result = $ldap->modify ( $dn,
changes => [
replace => @$whatToChange
]
);
return $result;
}
#######################################
#
# MODIFY using a ARRAY
#
my @ReplaceArray = ( 'keyword', "xxxxxxxxxx" ,
'proxy' , "yyyyyyyyyy" );
my $result = LDAPmodifyUsingArray ( $ldap, $dn, \@ReplaceArray );
sub LDAPmodifyUsingArray
{
my ($ldap, $dn, $whatToChange ) = @_;
my $result = $ldap->modify ( $dn,
changes => [
replace => [ @$whatToChange ]
]
);
return $result;
}
#######################################
#
# MODIFY an existing record using 'Changes'
# (or combination of add/delete/replace)
#
my @whatToChange;
my @ReplaceArray;
my @DeleteArray;
my @AddArray;
push @AddArray, 'cn', "me myself";
push @ReplaceArray, 'sn', '!@#$%^&*()__+Hello There';
push @ReplaceArray, 'cn', "me myself I";
push @DeleteArray, 'cn', "me myself";
if ( $#ReplaceArray > 0 ) {
push @whatToChange, 'replace';
push @whatToChange, \@ReplaceArray;
}
if ( $#DeleteArray > 0 ) {
push @whatToChange, 'delete';
push @whatToChange, \@DeleteArray;
}
if ( $#AddArray > 0 ) {
push @whatToChange, 'add';
push @whatToChange, \@AddArray;
}
$result = LDAPmodify ( $ldap, $dn, \@whatToChange );
sub LDAPmodify
{
my ($ldap, $dn, $whatToChange) = @_;
my $result = $ldap->modify ( $dn,
changes => [
@$whatToChange
]
);
return $result;
}
π OPERATION - Changing the RDN
Changing the RDN uses moddn with newrdn, deleteoldrdn => '1', and newsuperior if the archive action is selected. In that case the branch is set to "ou=newbranch, o=mycompany, c=mycountry". π
my $newRDN = "cn=Joseph User";
my $result = LDAPrdnChange ( $ldap, $dn, $newRDN, "archive" );
sub LDAPrdnChange
{
my ($ldap,$dn,$whatToChange,$action) = @_;
my $branch;
#
# if the archive action is selected, move this
# entry to another place in the directory.
#
if ( $action =~ /archive/i ) {
$branch = "ou=newbranch, o=mycompany, c=mycountry";
}
#
# use the 'deleteoldrdn' to keep from getting
# multivalues in the NAMING attribute.
# in most cases that would be the 'CN' attribute
#
my $result = $ldap->moddn ( $dn,
newrdn => $whatToChange,
deleteoldrdn => '1',
newsuperior => $branch
);
return $result;
}
β OPERATION - Adding a new Record
Check with your Directory Schema or Administrator for the correct objectClass β the doc says itβs sure itβll be different. Also: this DN MUST be changed to meet your implementation.
NOTE: the DN MUST be changed to meet your implementation.
my $DNbranch = "ou=bailiwick, o=mycompany, c=mycountry";
#
# check with your Directory Schema or Administrator
# for the correct objectClass... I'm sure it'll be different
#
my $CreateArray = [
objectClass => [ "top", "person", "organizationalPerson", "inetOrgPerson" ],
cn => "Jane User",
uid => "0000001",
sn => "User",
mail => 'JaneUser@mycompany.com'
];
#
# create the new DN to look like this
# " cn=Jo User + uid=0000001 , ou=bailiwick, o=mycompany, c=mycountry "
#
# NOTE: this DN MUST be changed to meet your implementation
#
my $NewDN = "@$CreateArray[2]=".
"@$CreateArray[3]+".
"@$CreateArray[4]=".
"@$CreateArray[5],".
$DNbranch;
LDAPentryCreate($ldap, $NewDN, $CreateArray);
#
# CreateArray is a reference to an anonymous array
# you have to dereference it in the subroutine it's
# passed to.
#
sub LDAPentryCreate
{
my ($ldap, $dn, $whatToCreate) = @_;
my $result = $ldap->add ( $dn, attrs => [ @$whatToCreate ] );
return $result;
}
π¨ ERROR - Retrieving and Displaying ERROR information
If code is truthy, weβve got an error, so record it with LDAPerror.
if ( $result->code ) {
#
# if we've got an error... record it
#
LDAPerror ( "Searching", $result );
}
sub LDAPerror
{
my ($from, $mesg) = @_;
print "Return code: ", $mesg->code;
print "\tMessage: ", $mesg->error_name;
print " :", $mesg->error_text;
print "MessageID: ", $mesg->mesg_id;
print "\tDN: ", $mesg->dn;
#---
# Programmer note:
#
# "$mesg->error" DOESN'T work!!!
#
#print "\tMessage: ", $mesg->error;
#-----
}
Programmer note: "$mesg->error" DOESN'T work!!! That line is commented out for a reason, bestie. π
π UNBIND
$ldap->unbind;
π LDAP SCHEMA RETRIEVAL π
okay so this next bit is literally the β¨main characterβ¨ move β grabbing the schema info off your directory server. here's the whole glow-up sequence, bestie π
step one π β you initialize a brand-new LDAP object, and it's the exact same procedure as listed at the very beginning of this document. no new tricks, i promise.
step two π¦ β you bind to your directory server. and like, heads up: some servers may require authentication to retrieve the schema from the directory server π so don't skip this. that procedure is also listed at the beginning of this document. you got this π«Ά
after a successful bind you're literally ready to pull the schema info. you do it by initializing a schema object, like:
$schema = $ldap->schema ( );
in this case Net::LDAP will attempt to determine the dn under which the schema can be found. first it will look for the attribute subschemaSubentry in the root DSE π and if that cannot be found, then it will default to the assumption of cn=schema. lowkey wild but okay π
alternatively β and ngl this is the iconic manual override β you can specify the dn where the schema is to be found with:
$schema = $ldap->schema ( dn => $dn );
once we have a dn to search for, Net::LDAP will fetch the schema entry with:
$mesg = $self->search ( base => $dn,
scope => 'base',
filter => '(objectClass=subschema)',
);
once the schema object has been initialized, schema methods are used to retrieve the data π₯ and there are a number of ways this can be done. info on the schema methods can be found in the Net::LDAP::Schema pod documentation. go read it, it's giving essential β¨
π the attribute-display code snippet π
the following is a code snippet showing how to get and display information about returned attributes:
#
# Get the attributes
#
@attributes = $schema->all_attributes ( );
#
# Display the attributes
#
foreach $ar ( @attributes ) {
print "attributeType: ", $ar->{name}, "\n";
#
# Print all the details
#
foreach $key ( keys %{$ar} ) {
print join ( "\n\t\t", "\t$key:",
ref ( $ar->{$key} ) ? @{$ar->{$key}} : $ar->{$key}
), "\n";
}
}
and here's the slay part π β the process is basically the same for getting objectClass information. wherever schema->all_attributes() is used, just substitute schema->all_objectclasses(). from that point on the process is the same for both objectClasses and attributes π like, copy-paste energy fr fr.
π BUGS π
None known, but there may be some π
π§ AUTHOR π§ (of this document)
Russell Biggs <rgb@ticnet.com>
πΈ COPYRIGHT πΈ
All rights to this document are hereby relinquished to Graham Barr.
okay that's the whole page bestie, you ate that π«Άβ¨ this lovely little doc is from perl v5.42.0, dated 2024-01-02, and it lives at Net::LD...Examples(3) β go forth and LDAP slay π
π
π¦ where this page comes from
- opensuse-leap 16.0: perl-ldap 0.68-160000.2.2 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms