Listing11_Iterate_Subnets (Perl)

This code can be found in Chapter 9 of Managing Enterprise Active Directory Services

Purchase XP Cookbook or Networking Recipes for only $25 plus shipping! While supplies last.

Find out how to download all of the Perl code from this site.

# From the book "Managing Enterprise Active Directory Services"
# ISBN: 0-672-32125-4

use strict;
use Net::LDAP;
use Net::LDAP::Control;
use Net::LDAP::Constant qw( LDAP_CONTROL_PAGED LDAP_CONTROL_SORTREQUEST );

# Could be dynamically found by querying RootDSE
my $base_dn = 'dc=xyz,dc=com';

my $server = 'dc1.xyz.com';
my $user   = 'administrator@xyz.com';
my $passwd = 'password';

my $ldap = Net::LDAP->new($server, version => 3) or die "$@";
my $result = $ldap->bind($user, password => $passwd);
$result->code && die $result->error;

my $page = Net::LDAP::Control->new( LDAP_CONTROL_PAGED,
                                    size => 500);
my $sort = Net::LDAP::Control->new( LDAP_CONTROL_SORTREQUEST,
                                    order => 'cn');
my @args = (base  => "cn=subnets,cn=sites,cn=configuration,$base_dn",
            scope => 'subtree',
            attrs => [ 'cn', 'siteObject' ],
            filter => '(&(objectClass=subnet)(objectCategory=Subnet))',
            control => [ $sort, $page ] );
my $count = 0;
while (defined ($result = $ldap->search( @args )) ) {
  $result->code && die $result->error;
  foreach my $entry($result->entries) {
      my $subnet = $entry->get_value('cn');
      my $site   = $entry->get_value('siteObject');
      # strip off everything but the name from the site DN
      $site   =~ s/^cn=(.+),cn=sites,cn=configuration.+$/$1/i;
      $count++;
      print "$count. $subnet ($site)\n";
   }
   my ($resp) = $result->control( LDAP_CONTROL_PAGED );
   last unless $resp->cookie && $page->cookie($resp->cookie);
}
$ldap->unbind;

This code has been viewed 776 times.

New from the creators of TechTasks.com: StatSheet.com