Skip to content
Browse files

shorten recursive-ldap-delete.pl and make it more "elegant"

  • Loading branch information...
1 parent cdeb93c commit 4fbd3e00ce2344b4e3e4aab9e7193cad9691f8d2 @marschap marschap committed Aug 13, 2005
Showing with 14 additions and 25 deletions.
  1. +14 −25 contrib/recursive-ldap-delete.pl
View
39 contrib/recursive-ldap-delete.pl
@@ -2,42 +2,31 @@
#
# recursive-ldap-delete.pl
#
-# Mike Jackson <mj@sci.fi>
+# originally by Mike Jackson <mj@sci.fi>
+# shortened by Peter Marschall <peter@adpm.de>
+# based on ideas by Norbert Kiesel <nkiesel@tbdetworks.com>
#
+# ToDo: check errors, handle references, ....
use strict;
use Net::LDAP;
my $server = "localhost";
my $binddn = "cn=directory manager";
my $bindpasswd = "foobar";
-my $base = "dc=bigcorp,dc=com";
-my $delbranch = "ou=users,$base"; # branch to remove
+my $delbranch = "ou=users,dc=bigcorp,dc=com"; # branch to remove
my $ldap = Net::LDAP->new( $server ) or die "$@";
$ldap->bind( $binddn, password => $bindpasswd, version => 3 );
-my $result = $ldap->search( base => $delbranch,
- filter => "(objectclass=*)" );
-
-my @dnlist;
-my $entry;
-foreach $entry ( $result->all_entries ) { push @dnlist, $entry->dn }
-# explode dn into an array and push
-# arrays to indexed hash of arrays
-my %HoL;
-my $i = 0;
-for ( @dnlist ) {
- s/,$base//;
- $HoL{$i} = [ split(",", $_) ];
- $i++;
-}
+my $search = $ldap->search( base => $delbranch,
+ filter => "(objectclass=*)" );
-# sorted descending by number of members (leaf nodes last)
-foreach my $key ( sort { @{$HoL{$b}} <=> @{$HoL{$a}} } keys %HoL ) {
- my $dn = join(",", @{ $HoL{$key} }).",$base";
- $ldap->delete($dn);
-}
+# delete the entries found in a sorted way:
+# those with more "," (= more elements) in their DN, which are deeper in the DIT, first
+# trick for the sorting: tr/,// returns number of , (see perlfaq4 for details)
+foreach my $e (sort { $b->dn =~ tr/,// <=> $a->dn =~ tr/,// } $search->entries()) {
+ $ldap->delete($e);
+}
-$entry->update ( $ldap );
-$ldap->unbind;
+$ldap->unbind();

0 comments on commit 4fbd3e0

Please sign in to comment.
Something went wrong with that request. Please try again.