Code:
#!/usr/bin/perl
#
# Copyright (c) 2004
# Ali Onur Cinar &060;cinar&064;zdo.com&062;
#
# License:
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for non-commercial purposes and without fee is hereby
# granted, provided that the above copyright notice appear in all copies
# and that both the copyright notice and this permission notice and
# warranty disclaimer appear in supporting documentation, and that the name
# of Ali Onur Cinar not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior permission.
#
# @author A. Onur Cinar <cinar(a)zdo.com># @version $Id: ldap2csv.pl,v 1.1 2004/12/07 15:12:38 cinar Exp $#
use Net::LDAP;
@fields = # fields to export
( # Label Field Name Index
['First Name', 'givenName' , 0], ['Last Name' , 'sn' , 0], ['Title' , 'title' , 0],
['Email' , 'mail' , 0], ['Email 2' , 'mail' , 1], ['Phone' , 'telephoneNumber', 0],
['Phone' , 'telephoneNumber', 1], ['Phone' , 'telephoneNumber', 2],
['Phone' , 'telephoneNumber', 3], ['Phone' , 'telephoneNumber', 4],
['Mobile' , 'mobile' , 0],
['Birthday' , 'birthday' , 0], ['Address' , 'street' , 0], ['Address' , 'street' , 1],
['Address' , 'street' , 2],
);
$ldap = Net::LDAP->new('localhost') or die "$@"; # open connection
$mesg = $ldap->bind( # login
"uid=test", password => "password");
$mesg = $ldap->search( # search
base => "dc=abc",
filter => "(objectClass=inetOrgPerson)"
);
$DATETIME=`date`;
sub get # get field value
{ return $_[0]->exists($_[1]) ? $_[0]->get($_[1])->[$_[2] ? $_[2] : 0] : '';}
print "$DATETIME"; # first line with file created date/time
print '"'.(join '","', "Report", # header map {$_->[0]} @fields)."\"\n";
foreach $entry ($mesg->all_entries) # for each entry
{
@dn = map {s/[a-z]+=//gi; $_ = ucfirst} # organization
reverse split /,/, $entry->dn;
shift @dn; shift @dn;
shift @dn; pop @dn;
print '"'
. (join '","', "@dn", # row map
{get $entry, $_->[1], $_->[2]} @fields)
. "\"\n";
}
$mesg = $ldap->unbind; # close connection