Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting CN's with LDAP?

Tags:

perl

ldap

I have this code

#!/usr/bin/perl

use warnings;
use strict;
use Net::LDAP;
use Data::Dumper;

my $dn="CN=...";
my $password="xxx";

my $ldap = Net::LDAP->new('example.com') or die "$@";
my $mesg = $ldap->bind($dn, password=>$password);
if ($mesg->code) { die "uuuu $mesg"; }

$mesg = $ldap->search(base => "dc=test,dc=example,dc=com", filter => "(name=LIST)",);

my $ref = $mesg->entry->get_value("member", asref => 1);
print Dumper $ref;

foreach my $string (@{$ref}) {
    $string =~ /CN=(.+?),.*/;
    print $1 . "\n";
}

which outputs the CN's using regular expressions:

aaaa
bbbb
cccc
...

Using Dumper can I see the structure

$VAR1 = [
          'CN=aaaa,OU=test,DC=test,DC=example,DC=com',
          'CN=bbbb,OU=test,DC=test,DC=example,DC=com',
          'CN=cccc,OU=test,DC=test,DC=example,DC=com',

So I am wondering if there is a more "LDAP" way to extract these CN's, instead of using regular expressions?

Update:

Based on Javs answer this is the solution.

my $ref = $mesg->entry->get_value("member", asref => 1);

foreach my $string (@{$ref}) {
    print ldap_explode_dn($string)->[0]{CN} . "\n";
}
like image 559
Sandra Schlichting Avatar asked Dec 08 '10 15:12

Sandra Schlichting


1 Answers

You can:

use Net::LDAP::Util qw(ldap_explode_dn);

and use it on your attribute like this:

ldap_explode_dn($mesg->entry->get_value('member'));

to get this array of hashes:

$VAR1 = [
      {
        'CN' => 'aaaa'
      },
      {
        'OU' => 'test'
      },
      {
        'DC' => 'test'
      },
      {
        'DC' => 'example'
      },
      {
        'DC' => 'com'
      }
    ];
like image 113
javs Avatar answered Nov 15 '22 05:11

javs