前述の設定が完了したら、http://search.cpan.org/~gbarr/perl-ldap-0.39/lib/Net/LDAP.pod に上げられているサンプルやリファレンスと、Perlの知識があれば、LDAPの操作が可能です。
以下は、LDAPサーバーのdc=example,dc=com以下からuidがtestで始まるユーザーを検索し、検索された件数を数えた後、新しくユーザーエントリを追加する一連の処理を記述したものです。(何度も言いますが…私はperlに明るくありません…)
test-ldap1.pl
use Net::LDAP;
#
# bind to LDAP.
#
$ldap = Net::LDAP->new( "localhost" );
$mesg = $ldap->bind( "cn=Directory Manager", password=>"password" );
if( $mesg->code == 0 ){
print "bind success\n";
} else {
warn "bind fail: ". $mesg->error;
exit( $mesg->error );
}
#
# search from LDAP and count user=test* user entry.
#
$baseDN = "dc=example,dc=com";
$searchResult = $ldap->search( base=>$baseDN, filter=>"uid=test*" );
$count=0;
foreach $entry ( $searchResult->entries ){
$count++;
}
print "uid=test* $count entries\n";
#
# add to LDAP.
#
$uid = "test." . $count;
$suffix = ",ou=People,dc=example,dc=com";
$dn = "uid=" . $uid . $suffix;
$addResult = $ldap->add( $dn,
attr => [
'cn' => $uid,
'sn' => $uid,
'mail' => $uid . '@example.com',
'uid' => $uid,
'objectClass' => [
'top',
'person',
'organizationalPerson',
'inetOrgPerson'
],
]
);
if ( $addResult->code == 0 ) {
print "added $dn\n";
} else {
$ldap->unbind;
warn "failed to add entry: ", $addResult->error, "\n";
exit( $addResult->code );
}
#
# search and dump added user.
#
$searchResult = $ldap->search( base=>$baseDN, filter=>"uid=".$uid );
foreach $entry ( $searchResult->entries ) {
$entry->dump
};
$ldap->unbind;
実行結果
# perl test-ldap1.pl
bind success
uid=test* 11 entries
added uid=test.11,ou=People,dc=example,dc=com
------------------------------------------------------------------------
dn:uid=test.11,ou=People,dc=example,dc=com
objectClass: person
organizationalPerson
inetOrgPerson
top
mail: test.11@example.com
uid: test.11
cn: test.11
sn: test.11
#
# ldapsearch -x -b "dc=example,dc=com" uid=test.11
dn: uid=test.11,ou=People,dc=example,dc=com
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
objectClass: top
mail: test.11@example.com
uid: test.11
cn: test.11
sn: test.11
#
WikiPedia [ perl ]に、O'Reillyの商売の邪魔をしない程度に、概要の説明がのっています。
http://ja.wikipedia.org/wiki/Perl
「始めてperl」も、時間があったら読んでみたいところです。確か、会社に一冊あったはずだが・・・現在は第3版になっているんだなぁ。
Perlの記述方法で、->, =>等が気になります。
-> 記号
Class->method
$object->method
$object->property
と言うように使用できるようです。Classはパッケージであり、メソッドはサブルーチンとのこと。
=> 記号
連想配列(ハッシュ)にアクセスする際に使用する。
Key=>value
%hash = ( 'one', 1, 'two', 2 ) と書いても良いし、
%hash = ( 'one'=>1, 'two'=>2 )と書いても良いようです。
配列の扱いが、LDAPのデータと非常によくマッチして違和感無く操作できそうです。