Access LDAP Server using Ruby
Recently I tried accessing LDAP server using ruby gem. I came to know about net-ldap gem which does the job in easier way. The Lightweight Directory Access Protocol (LDAP) is an application protocol for accessing and maintaining distributed directory information services over an Internet Protocol. Let’s see how to access information from LDAP using net-ldap gem.
1. First, Install the gem as
gem install net-ldap
2. Initiate LDAP server as follows
require 'rubygems' require 'net/ldap' ldap = Net::LDAP.new ldap.host = "x500.bund.de" ldap.port = "389" is_authorized = ldap.bind
x500.bund.de is public LDAP server. You can find various public ldap server in net.
3. If suppose we need to authenticate Ldap server using username and password. We can do it as
ldap = Net::LDAP.new ldap.host = "x500.bund.de" ldap.port = "389" username = "xxxxxxxx" pasword = "xxxxxxxxx" ldap.auth username, password is_authorized = ldap.bind #returns true if auto works
4. Now let see how to search some records in LDAP server
attrs =  ldap.search( :base => "l=init,ou=Service,o=Bund,c=DE", :attributes => attrs, :return_result => true ) do |entry| # entry is records returned after search end
Here entry will return set of records that matching the word given in base.
5. We can also use filter to refine our search as
filter = Net::LDAP::Filter.eq("username", "xxxxx") attrs =  ldap.search(:base => treebase, :filter => filter, :attributes => attrs, #refined search end
I hope this blog will be useful for accessing Ldap server using ruby gem. Any suggestion or comments are most welcome