Monday, October 27, 2008

This one is better: ruby-net-ldap

After posting a quick how-to about Ruby-LDAP, I received a couple of very helpful comments that pointed me towards ruby-net-ldap. This is a pure Ruby LDAP library that is stable and has good documentation to help you along. It is the best Ruby LDAP gem out there and I've been through almost all of them to get to this point.

Here is a simple search for an organizational unit with the name "marketing"...


require 'rubygems'
require 'net/ldap'

def ldap_search

 ldap = Net::LDAP.new
 ldap.host = "localhost"
 ldap.port = "389"
 ldap.auth "cn=Directory Manager", "password"

 filter = Net::LDAP::Filter.eq( "ou", "marketing" )
 attrs = [ "ou" , "objectClass"]

 ldap.search( :base => "dc=mycompany, dc=com", :attributes => attrs, :filter =>
 filter, :return_result => true ) do |entry|
   puts entry.dn
 end

end


Here is the code to add an organizational unit under the base node...


require 'rubygems'
require 'net/ldap'

def ldap_search

 ldap = Net::LDAP.new
 ldap.host = "localhost"
 ldap.port = "389"
 ldap.auth "cn=Directory Manager", "password"

 dn = "ou=marketing, dc=mycompany, dc=com"
 attr = {
   :ou => "marketing",
   :objectclass =>"organizationalUnit"
 }
 ldap.add( :dn => dn, :attributes => attr )

end



Check out the rest of the documentation for pretty good examples. This is the library I recommend. In my situation, I'm using ruby-net-ldap to import data in to, manipulate and query data in an OpenDS LDAP server.

6 comments:

Jon Gillies said...

Good find! Nice to have a native Ruby implementation of LDAP.

Cowlibob said...

current link to the docs:

http://net-ldap.rubyforge.org/rdoc/

Katie said...

Great help! Do you know how to combine filters? For instance, I want to pull back a list of all enabled users...

Thanks!

BaroqueBobcat said...

Katie,
Net::LDAP::Filter defines & and | so you could do

filter = Net::LDAP::Filter.eq('objectclass', 'Person') & Net::LDAP::Filter.eq('name', 'bob')

ldap.search :base=> base, :filter => filter

or something.

Katie said...

Thanks BaroqueBobcat - that will help, since right now I have 2 filters defined, which I then combine in my search string. Like this:

filter1 = Net::LDAP::Filter.eq("objectCategory","user")
filter2 = Net::LDAP::Filter.eq("userAccountControl","512")

ldap.search(:base => treebase, :filter => filter1 & filter2, :attributes => attrs ) do |entry| @usernames << entry.cn
end

So, the "&" will help! Thanks again.

glacius said...

How would one check if an attribute is blank or empty