How to read the contents of a variable with Netldap

78 Views Asked by At

I'm writing a script that receives as a parameter the name of a user and performs a search in LDAP but I can't find a way to use a Perl variable in the LDAP search filter.

The code used is this one :

package cnmodule;

sub function1 {

  use strict;
  use Net::LDAP;

  my ($local) = @_;
  my $valueA;

  my $ldap = Net::LDAP->new('ad.network',version => 3) 
    or die "Can t connect to LDAP ($@)";

  $valueA = $ldap->bind ("cn=usercheck,cn=users,dc=domain,dc=network", password => 'password'); 
  $valueA->code && die $valueA->error;

  $valueA= $ldap->search(
    base => 'dc=domain,dc=network',
    scope => 'sub',
    filter => '(sn=$local)', 
  );

  $ldap->unbind();

  $valueA->code && die $valueA->error;
  foreach my $entry ($valueA->all_entries) {
    my $valueB = $entry->get_value('CN'); 
  }
  return $valueB;
}

$variableA='test';
$variableB=function1($variableA);
print $variableB;
1;

The variable "$local" contains the name I need to do the search and is used in the ldap filter, but with this script LDAP doesn't receive the content of this variable and therefore doesn't return anything.

Does anyone have a solution for me?

1

There are 1 best solutions below

0
On BEST ANSWER

Your problem is here:

$valueA= $ldap->search(
  base => 'dc=domain,dc=network',
  scope => 'sub',
  filter => '(sn=$local)', 
);

Or, more specifically, here:

  filter => '(sn=$local)',

Perl (like many programming languages) doesn't expand variables in a single-quoted string. So you're sending the literal string (sn=$local). The fix is simple - change to using a double-quoted string.

  filter => "(sn=$local)",