无法处理perl LDAP搜索

时间:2012-10-30 14:38:06

标签: perl ldap

这是我在StackOverFlow上的第一个问题,所以如果我做错了,请告诉我。

我正在编写一个perl脚本来执行LDAP搜索,以识别用户所属的列表组。我阅读了关于这个主题的perldocs,并在这个网站上找到了一些例子,但是我无法让脚本正常运行。

这是我的代码:

#!/usr/bin/perl

use strict;
use warnings;
use Net::LDAP;

my $ldap;
my $ldapuser = "MVS\\user";
my $ldappass = "passw0rd";
my $searchbase = "DC=dom,DC=site,DC=labs,DC=domain,DC=net";
my $attrs = "sAMAccountName, sn, givenname, memberOf";
my $filter="(samAccountName=user)";
my $result;

# ensure the ldap connection is made
print "Connecting to LDAP...\n";
$_ = $ldap = Net::LDAP->new('dc1.mvs.cso.labs.rim.net')     or die "$@";

# ensure the bind is successful
print 'Binding....';
$_ = $ldap->bind ("$ldapuser", password=>$ldappass, version=>3);
print $_->error_text();


$result = $ldap->search(base=>"$searchbase", filter=>"$filter", attrs=>[$attrs]);

my $max;
my $i;
my $entry;
my $first;
my $last;
my $login;
my @memberOf;

$max = $result->count;
print "Count: $max\n";

for ($i=0;$i<$max;$i++) {
$entry = $result->entry($i);
$last = $entry->get_value('sn');
$login = $entry->get_value('sAMAccountName');
@memberOf = $entry->get_value('memberOf');

print "$first $last\n";
print "$login\n";
print "@memberOf\n";

}
$ldap->unbind;
$ldap->disconnect;

以下是运行此代码时的结果:

Connecting to LDAP...

Binding....Operation completed without error
Count: 1
Use of uninitialized value $first in concatenation (.) or string at ./ldap_test.cgi line 43, <DATA> line 604.
Use of uninitialized value $last in concatenation (.) or string at ./ldap_test.cgi line 43, <DATA> line 604.
Use of uninitialized value $login in concatenation (.) or string at ./ldap_test.cgi line 44, <DATA> line 604.

据我所知,在我运行时,$ entry没有得到任何值:

$entry = $result->entry($i);

但我可能错了。 任何帮助将不胜感激。

谢谢,

1 个答案:

答案 0 :(得分:4)

问题出在搜索的属性部分。你给它一个字符串,它期待一个数组引用。

错误:

my $attrs = "sAMAccountName, sn, givenname, memberOf";
$result = $ldap->search(base=>"$searchbase", filter=>"$filter", attrs=>[$attrs]);

好:

my $attrs = ["sAMAccountName", "sn", "givenname", "memberOf"];
$result = $ldap->search(base=>"$searchbase", filter=>"$filter", attrs=>$attrs);