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.
9 comments:
Good find! Nice to have a native Ruby implementation of LDAP.
current link to the docs:
http://net-ldap.rubyforge.org/rdoc/
Great help! Do you know how to combine filters? For instance, I want to pull back a list of all enabled users...
Thanks!
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.
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.
How would one check if an attribute is blank or empty
Thanks. Helped me out heaps.
Note that ruby-net-ldap is the old, not-updated-in-5-years code; it is the net-ldap gem that you really want.
I also have example usage of it documented on Stack Overflow.
I have a need to search in AD by DN attribute. For some reason this search comes with zero results (empty array). I can successfully search by any other attributes but not DN. I am puzzled as to why this would be the case and wonder if anyone has an explanation. I am currently using a workaround where I use multiple filters to search for all params that makeup the DN but I would prefer to just search for DN or at least understand why this is not posible. Thanks!
Post a Comment