Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Deleting a Subtree from LDAP

by mayaTheCat (Scribe)
on Sep 17, 2003 at 20:39 UTC ( [id://292251]=sourcecode: print w/replies, xml ) Need Help??
Category: Utility Scripts
Author/Contact Info mayaTheCat
Description: hi monks,

the following code recursively deletes a subtree from LDAP;
since, only leaf nodes can be deleted from ldap, this code, firstly, traverses the subtree, and then deletes the node in the reverse order it has been traversed.

if the port is other than the default port (389), it can be appended at the back of the server string, delimited with a ':';
e.g. if the server is ldapserver and the port is 889, then the following string works: 'ldapserver:889'.

if we do not want to stress the server, we can periodically pause the deletion for a while through the parameters $sleepPeriod and sleepDuration

sub ldapRecursiveDelete {
    my ($server, $subtreeDN, $user, $password, $sleepPeriod, $sleepDur
+ation) = @_;
    my ($ldap, @toBeSearched, @toBeDeleted);

    return unless defined $subtreeDN;
    $sleepPeriod = 2000 unless defined $sleepPeriod;
    $sleepDuration = 1 unless defined $sleepDuration;

    use Net::LDAP;

    $ldap = Net::LDAP->new($server);

    if (defined $user && defined $password) {
        $ldap->bind($user, password => $password);
    } else {
        $ldap->bind;
    }

    @toBeSearched = ( $subtreeDN );

    while (@toBeSearched) {
        $_ = shift @toBeSearched;

        push @toBeDeleted, $_;

        for (
            (
                $ldap->search(
                    base => $_
                    , scope => 'one'
                    , filter => '(objectclass=*)'
                    , attrs => [ '1.1' ]
                )
            )->entries
        ) {
            push @toBeSearched, $_->dn;
        }
    }

    my $i = 0;
    while (@toBeDeleted) {
        $ldap->delete(pop @toBeDeleted);
        sleep $sleepDuration unless ++$i % $sleepPeriod;
    }

    $ldap->unbind;
}

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: sourcecode [id://292251]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-19 06:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found