Search code examples
perlhashldapdn

LDAP Search for User DN Returns a Hash - Perl


All I am trying to do is search for a user and return the user's DN in a Perl script. However, my script is printing a reference to a hash instead of the actual DN of the user.

The DN needs to be put into another variable later on so I need the DN to be right.

Here is my code:

use strict;
use warnings;

use Net::LDAPS;
use Net::LDAP;
use Config::Simple;
use Try::Tiny;

#LDAP connection.
my $ldap;

my $hostname = "Hostname";
my $port = 2389;
my $rootDN = "username";
my $password = "password";

#Connect to LDAP
$ldap = Net::LDAP->new( $hostname, port => $port ) or die $@;

#Send username and password
my $mesg = $ldap->bind(dn => $rootDN, password => $password) or die $@;


my $result = $ldap->search(
  base   => "ou=AllProfiles",
  filter => "(cn=Alice Lee)",
  attrs => ['*','entrydn'],
);

my $href = $result;
print "$href\n";

Here is my output:

enter image description here

Does anyone know why I am getting this? Or know how to fix it?

Thanks!


Solution

  • You get back a whole object which you need to get the results from, and from that, navigate to what you want. I believe this will work, if indeed "entrydn" is the correct name.

    my $entries = $result->entries;
    my $dn = $entries[0]->get_value('entrydn');
    

    (If you expect to return more than one entry, of course you will have to iterate. If you may get no results, you need to check for that too.)