Searching Active Directory with Perl, Page 3
Building Static Contact Directories
I always like to incorporate a real-world examples into my tutorials. In this tutorial, I'll show you how to create static Web-based copies of the staff directory. Why would you want to do this, you ask? Even though LDAP is read-optimized, it just doesn't make sense to constantly query the directory server for rarely changing contact information. Nonetheless, the Web-based version of the directory should always contain the latest information. The answer? A Perl script which generates these directories nightly!
Note. You can view a live example of the results of this script on the Fisher College of Business Web site.
#!/usr/bin/perl
use strict;
use Net::LDAP;
# Connect and bind
my $ad = Net::LDAP->new("ad.wjgilmore.com")
or die "Could not connect!";
$ad->bind("ad-web\@ad.wjgilmore.com", password=>"secret");
# build the alphabetical toc
my $letter = 'a';
my $toc = "";
for(my $index=0; $index<26; $index++) {
$toc .= "$letter ";
$letter++;
}
$toc .= "
";
# Perform LDAP queries, build directory pages
$letter = 'a';
my $base = 'OU=People,OU=staff,DC=ad,DC=wjgilmore,DC=com';
for(my $index=0; $index<26; $index++) {
# Filter on the staff membership and
# first letter of samaccountname attribute
my $filter = "(&
(memberof=CN=staff,OU=groups,DC=ad,DC=wjgilmore,DC=com)
(samaccountname=$letter*))";
# Which attributes should be returned?
my $attrs = "sn, givenname, mail";
# Execute the search
my $results = $ad->search(base=>$base,filter=>$filter,attrs=>$attrs);
# How many entries returned?
# Build the directory
my $count = $results->count;
my $entry;
my $directory;
for (my $i=0; $i<$count; $i++) {
$entry = $results->entry($i);
$directory .= $entry->get_value('givenname')." ".
$entry->get_value('sn').
" (".$entry->get_value('mail').")".
"
\n";
}
# Write the file
open(FILE, "> /www/wjgilmore/directory/$letter.html");
print FILE $toc;
print FILE $directory;
close FILE;
$letter++;
}
# Unbind from the server
$ad->unbind;
Sample output is shown in Figure 1-1:

Conclusion
I welcome questions and comments! E-mail me at jason@wjgilmore.com . I'd also like to hear more about your experiences integrating Microsoft and Open Source technologies!
About the Author
W. Jason Gilmore (http://www.wjgilmore.com/
) is an Internet application developer for the Fisher College of Business. He's the author of the upcoming book, PHP 5 and MySQL: Novice to Pro, due out by Apress in 2004.
His work has been featured within many of the computing industry's leading
publications, including Linux Magazine, O'Reillynet, Devshed, Zend.com, and
Webreview. Jason is also the author of A Programmer's Introduction to PHP
4.0 (453pp., Apress). Along with colleague Jon Shoberg, he's co-author of
"Out in the Open," a monthly column published within Linux magazine.
