I love Free Software!

Pages

Funny Quotes to Think

When you say "I wrote a program that crashed Windows", people just stare at You blankly and say "Hey, I got those with the system, for free"

-Torvalds, Linus(1995-03-08)-

Friday, October 9, 2009

Using Perl for Managing LDAP

Perl script for adding LDAP attributes

For accessing LDAP database from perl scripts install Net::LDAP perl module.
# aptitude install libnet-ldap-perl 
 
Script will search for DN which have mail attribute and objectClass is  
posixGroup 
Script only return the group which does not have attribute company 
Script will add attribute company and value blablabla to those DN returned by
search filter  
 
#!/usr/bin/perl
# This script is used for adding new attribute and values 
 
use Net::LDAP;
$ldap = Net::LDAP->new("localhost");
$ldap->bind("cn=admin,dc=example,dc=com", password=>"secret");
$mesg = $ldap->search(filter=>"(&(mail=*)(&(objectclass=posixGroup)\
                                    (!(company=*))))",base=>"dc=example,dc=com");
@entries = $mesg->entries;
foreach $entry (@entries){
       print "DN: " . $entry->dn(). "\n";
       $mesg = $ldap->modify ($entry->dn(), \
               add => {"company" => "blablabla"});
}

Delete LDAP attribute using Perl scripts

If you want to delete any attribute. You can use this in ldapmodify section  

# $mesg = $ldap->modify ($entry->dn(), delete => { company => [] });

How to Add multiple values for an attributes

We require two files in which one file contains list of group DN (Here referred as group_list) and another contains list of employees name that to be added to employee (referred as employees.txt in this script)
Script will set company value to blablabla and add each employees to employee Create a script add_employee.pl with below content 


#!/usr/bin/perl

use Net::LDAP;

$ldap = Net::LDAP->new("localhost");
$ldap->bind("cn=admin,dc=example,dc=com", password=>"secret");
while(<>) {
      chomp $_;
      $dn = $_;
      print "DN: $_.\n";
      $mesg = $ldap->modify ($dn, add => {"company" => "blablabla"});
      open (MYFILE, 'employees.txt');
      while () {
                        chomp;
                        print "$_\n";
                        $mesg = $ldap->modify($dn, add => { "employee" => "$_"} );
      }
close (MYFILE);
}
$ldap->unbind();
Run script group_policy.pl using below command

#  cat group_list| ./add_employee.pl

No comments:

Post a Comment