20081205 point restore of ldap entries - plembo/onemoretech GitHub Wiki

title: Point Restore of LDAP Entries link: https://onemoretech.wordpress.com/2008/12/05/point-restore-of-ldap-entries/ author: lembobro description: post_id: 422 created: 2008/12/05 16:01:20 created_gmt: 2008/12/05 16:01:20 comment_status: open post_name: point-restore-of-ldap-entries status: publish post_type: post

Point Restore of LDAP Entries

So, you do snap an LDIF backup of your LDAP directory every night, right? If you don’t, start. Tonight. If you do, this bit of code may come in handy. It lets you do a point restore of a specific LDAP entry from that big LDIF.

#!/usr/bin/perl
use strict;
use Net::LDAP;
use Net::LDAP::Entry;
use Net::LDAP::LDIF;

my $HOME = $ENV{'HOME'};
my $DSHOME = "/opt/sun/directory5.1";
my $instance = "slapd-bighost-user1";
my $ldifname = "2007_01_25_013000.ldif";
my $inldif = "$DSHOME/$instance/ldif/$ldifname";
my $outldif = "$HOME/data/admin/restore.ldif";
my $uid = "B12345";

my $ldif = Net::LDAP::LDIF->new($inldif, 'r') or die $!;
my $ldifw = Net::LDAP::LDIF->new($outldif, 'w') or die $!;

while (not $ldif->eof() ) {
	my $entry = $ldif->read_entry();
	if ($ldif->error() ) {
		print "tError! ",$ldif->error(),"n";

	}

	else {
		my $dn = $entry->dn;
		if ($dn =~ /$uid/gi) {
			$ldifw->write_entry($entry);
		}
	}
}
$ldifw->done;
$ldif->done;

__END__;

Why not just open the file up with vi and copy and past the text into another file? Because depending on the size of your database, that file may not load comfortably into vi. Besides, why go through all that trouble when a script can do the work for you. Here’s a variation on the above, this time reading a list of user IDs and grabbing any matches from the LDIF backup:

#!/usr/bin/perl
use strict;
use Text::ParseWords;
use Net::LDAP;
use Net::LDAP::Entry;
use Net::LDAP::LDIF;

my $HOME = $ENV{'HOME'};
my $inldif = "$HOME/data/2008_11_30_232000.ldif";
my $infile = "$HOME/data/prodrestores.csv";
my $outldif = "$HOME/data/prodrestores.ldif";

open FH, ">$outldif" or die $!;
close FH;
open FH, "new($inldif, ‘r’) or die $!;
	my $ldifw = Net::LDAP::LDIF->new($outldif, ‘a’) or die $!;

	while (not $ldif->eof() ) {
		my $entry = $ldif->read_entry();
		my $dn = $entry->dn;
		if ($dn =~ /$userid/gi) {
			print “t”, $dn, “n”;
			$ldifw->write_entry($entry);
		}
	}
	$ldifw->done;
	$ldif->done;
}
close FH;

__END__;

Note that in this case you have to run through the entire LDIF backup for each ID listed, which can take some time (not to mention CPU and memory), especially if you’ve got more than a few entries to restore. In such cases I’d highly recommend doing the work somewhere other than your directory server. You might also consider making a fresh pot of coffee for the office while you wait for the results.

Copyright 2004-2019 Phil Lembo