PerlでLDAPアクセス(use Net::LDAP)
#!/usr/bin/perl use strict; use warnings; use Net::LDAP; my $argv = shift; die "usage: $0 args\n" unless (defined $argv); my $ldap_srv = 'localhost'; my $ldap_port = '389'; my $dn = 'cn=Manager, dc=my-domain, dc=com'; my $dn_pass = 'password'; my $ldap = Net::LDAP->new($ldap_srv, port => $ldap_port) or die $!; my $mesg = $ldap->bind( $dn, password => $dn_pass, ); $mesg = $ldap->search( base => "ou=People, dc=my-domain, dc=com", scope => "sub", filter => "(cn=$argv)", ); $mesg->code && die $mesg->error; if ($mesg->count > 0) { foreach my $entry ($mesg->entries) { $entry->dump; } } $ldap->unbind; exit 0; __END__
こんな感じで出力されます。
$ ./ldap.pl test1 ------------------------------------------------------------------------ dn:uid=test1,ou=People,dc=my-domain,dc=com uid: test1 cn: test1 objectClass: account posixAccount shadowAccount userPassword: {SSHA}hlUFs7ZhrevI2BUZOEMlnpx7laUaBEtu shadowLastChange: 14629 shadowMax: 99999 shadowWarning: 7 loginShell: /bin/bash uidNumber: 1 gidNumber: 1 homeDirectory: /home/test1 gecos: test1
出力をLDIF形式にしたい場合は、"Net::LDAP::LDIF"を使います。
use Net::LDAP::LDIF; if ($mesg->count > 0) { my $ldif = Net::LDAP::LDIF->new(\*STDOUT, "w") or die $!; $ldif->write($mesg->all_entries); }
こんな感じです。
$ ./ldap.pl test1 dn: uid=test1,ou=People,dc=my-domain,dc=com uid: test1 cn: test1 objectClass: account objectClass: posixAccount objectClass: shadowAccount userPassword: {SSHA}hlUFs7ZhrevI2BUZOEMlnpx7laUaBEtu shadowLastChange: 14629 shadowMax: 99999 shadowWarning: 7 loginShell: /bin/bash uidNumber: 1 gidNumber: 1 homeDirectory: /home/test1 gecos: test1
エントリの追加や削除・修正は、"$ldap->add"・"$ldap->delete"・"$ldap->modify"で行います。
Net::LDAP - Lightweight Directory Access Protocol - metacpan.org
Net::LDAP::LDIF - LDIF reading and writing - metacpan.org