Object
This library provides a pure-Ruby implementation of the LDAP client protocol, per RFC-2251. It can be used to access any server which implements the LDAP protocol.
Net::LDAP is intended to provide full LDAP functionality while hiding the more arcane aspects the LDAP protocol itself, and thus presenting as Ruby-like a programming interface as possible.
require 'rubygems' require 'net/ldap' ldap = Net::LDAP.new ldap.host = your_server_ip_address ldap.port = 389 ldap.auth "joe_user", "opensesame" if ldap.bind # authentication succeeded else # authentication failed end
require 'rubygems' require 'net/ldap' ldap = Net::LDAP.new :host => server_ip_address, :port => 389, :auth => { :method => :simple, :username => "cn=manager,dc=example,dc=com", :password => "opensesame" } filter = Net::LDAP::Filter.eq( "cn", "George*" ) treebase = "dc=example,dc=com" ldap.search( :base => treebase, :filter => filter ) do |entry| puts "DN: #{entry.dn}" entry.each do |attribute, values| puts " #{attribute}:" values.each do |value| puts " --->#{value}" end end end p ldap.get_operation_result
We’re going to provide a quick, informal introduction to LDAP terminology and typical operations. If you’re comfortable with this material, skip ahead to “How to use Net::LDAP.” If you want a more rigorous treatment of this material, we recommend you start with the various IETF and ITU standards that relate to LDAP.
LDAP is an Internet-standard protocol used to access directory servers. The basic search unit is the entity, which corresponds to a person or other domain-specific object. A directory service which supports the LDAP protocol typically stores information about a number of entities.
LDAP servers are typically used to access information about people, but also very often about such items as printers, computers, and other resources. To reflect this, LDAP uses the term entity, or less commonly, principal, to denote its basic data-storage unit.
In LDAP’s view of the world, an entity is uniquely identified by a globally-unique text string called a Distinguished Name, originally defined in the X.400 standards from which LDAP is ultimately derived. Much like a DNS hostname, a DN is a “flattened” text representation of a string of tree nodes. Also like DNS (and unlike Java package names), a DN expresses a chain of tree-nodes written from left to right in order from the most-resolved node to the most-general one.
If you know the DN of a person or other entity, then you can query an LDAP-enabled directory for information (attributes) about the entity. Alternatively, you can query the directory for a list of DNs matching a set of criteria that you supply.
In the LDAP view of the world, a DN uniquely identifies an entity. Information about the entity is stored as a set of Attributes. An attribute is a text string which is associated with zero or more values. Most LDAP-enabled directories store a well-standardized range of attributes, and constrain their values according to standard rules.
A good example of an attribute is sn, which stands for “Surname.” This attribute is generally used to store a person’s surname, or last name. Most directories enforce the standard convention that an entity’s sn attribute have exactly one value. In LDAP jargon, that means that sn must be present and single-valued.
Another attribute is mail, which is used to store email addresses. (No, there is no attribute called “email,” perhaps because X.400 terminology predates the invention of the term email.) mail differs from sn in that most directories permit any number of values for the mail attribute, including zero.
We said above that X.400 Distinguished Names are globally unique. In a manner reminiscent of DNS, LDAP supposes that each directory server contains authoritative attribute data for a set of DNs corresponding to a specific sub-tree of the (notional) global directory tree. This subtree is generally configured into a directory server when it is created. It matters for this discussion because most servers will not allow you to query them unless you specify a correct tree-base.
Let’s say you work for the engineering department of Big Company, Inc., whose internet domain is bigcompany.com. You may find that your departmental directory is stored in a server with a defined tree-base of
ou=engineering,dc=bigcompany,dc=com
You will need to supply this string as the tree-base when querying this directory. (Ou is a very old X.400 term meaning “organizational unit.” Dc is a more recent term meaning “domain component.”)
(stub, discuss v2 and v3)
The essential operations are: #, #, #, #, #, and #.
# supplies a user’s authentication credentials to a server, which in turn verifies or rejects them. There is a range of possibilities for credentials, but most directories support a simple username and password authentication.
Taken by itself, # can be used to authenticate a user against information stored in a directory, for example to permit or deny access to some other resource. In terms of the other LDAP operations, most directories require a successful # to be performed before the other operations will be permitted. Some servers permit certain operations to be performed with an “anonymous” binding, meaning that no credentials are presented by the user. (We’re glossing over a lot of platform-specific detail here.)
Calling # against the directory involves specifying a treebase, a set of search filters, and a list of attribute values. The filters specify ranges of possible values for particular attributes. Multiple filters can be joined together with AND, OR, and NOT operators. A server will respond to a # by returning a list of matching DNs together with a set of attribute values for each entity, depending on what attributes the search requested.
# specifies a new DN and an initial set of attribute values. If the operation succeeds, a new entity with the corresponding DN and attributes is added to the directory.
# specifies an entity DN, and a list of attribute operations. # is used to change the attribute values stored in the directory for a particular entity. # may add or delete attributes (which are lists of values) or it change attributes by adding to or deleting from their values. Net::LDAP provides three easier methods to modify an entry’s attribute values: #, #, and #.
# specifies an entity DN. If it succeeds, the entity and all its attributes is removed from the directory.
# (or #) is an operation added to version 3 of the LDAP protocol. It responds to the often-arising need to change the DN of an entity without discarding its attribute values. In earlier LDAP versions, the only way to do this was to delete the whole entity and add it again with a different DN.
# works by taking an “old” DN (the one to change) and a “new RDN,” which is the left-most part of the DN string. If successful, # changes the entity DN so that its left-most node corresponds to the new RDN given in the request. (RDN, or “relative distinguished name,” denotes a single tree-node as expressed in a DN, which is a chain of tree nodes.)
To access Net::LDAP functionality in your Ruby programs, start by requiring the library:
require 'net/ldap'
If you installed the Gem version of Net::LDAP, and depending on your version of Ruby and rubygems, you may also need to require rubygems explicitly:
require 'rubygems' require 'net/ldap'
Most operations with Net::LDAP start by instantiating a Net::LDAP object. The constructor for this object takes arguments specifying the network location (address and port) of the LDAP server, and also the binding (authentication) credentials, typically a username and password. Given an object of class Net:LDAP, you can then perform LDAP operations by calling instance methods on the object. These are documented with usage examples below.
The Net::LDAP library is designed to be very disciplined about how it makes network connections to servers. This is different from many of the standard native-code libraries that are provided on most platforms, which share bloodlines with the original Netscape/Michigan LDAP client implementations. These libraries sought to insulate user code from the workings of the network. This is a good idea of course, but the practical effect has been confusing and many difficult bugs have been caused by the opacity of the native libraries, and their variable behavior across platforms.
In general, Net::LDAP instance methods which invoke server operations make a connection to the server when the method is called. They execute the operation (typically binding first) and then disconnect from the server. The exception is Net::LDAP#open, which makes a connection to the server and then keeps it open while it executes a user-supplied block. Net::LDAP#open closes the connection on completion of the block.
Instantiate an object of type Net::LDAP to perform directory operations. This constructor takes a Hash containing arguments, all of which are either optional or may be specified later with other methods as described below. The following arguments are supported:
:host => the LDAP server’s IP-address (default 127.0.0.1)
:port => the LDAP server’s TCP port (default 389)
:auth => a Hash containing authorization parameters. Currently supported values include: {:method => :anonymous} and {:method => :simple, :username => your_user_name, :password => your_password } The password parameter may be a Proc that returns a String.
:base => a default treebase parameter for searches performed against the LDAP server. If you don’t give this value, then each call to # must specify a treebase parameter. If you do give this value, then it will be used in subsequent calls to # that do not specify a treebase. If you give a treebase value in any particular call to #, that value will override any treebase value you give here.
:encryption => specifies the encryption to be used in communicating with the LDAP server. The value is either a Hash containing additional parameters, or the Symbol :simple_tls, which is equivalent to specifying the Hash {:method => :simple_tls}. There is a fairly large range of potential values that may be given for this parameter. See # for details.
Instantiating a Net::LDAP object does not result in network traffic to the LDAP server. It simply stores the connection and binding parameters in the object.
# File lib/net/ldap.rb, line 349 349: def initialize args = {} 350: @host = args[:host] || DefaultHost 351: @port = args[:port] || DefaultPort 352: @verbose = false # Make this configurable with a switch on the class. 353: @auth = args[:auth] || DefaultAuth 354: @base = args[:base] || DefaultTreebase 355: encryption args[:encryption] # may be nil 356: 357: if pr = @auth[:password] and pr.respond_to?(:call) 358: @auth[:password] = pr.call 359: end 360: 361: # This variable is only set when we are created with LDAP::open. 362: # All of our internal methods will connect using it, or else 363: # they will create their own. 364: @open_connection = nil 365: end
# takes the same parameters as #. # makes a network connection to the LDAP server and then passes a newly-created Net::LDAP object to the caller-supplied block. Within the block, you can call any of the instance methods of Net::LDAP to perform operations against the LDAP directory. # will perform all the operations in the user-supplied block on the same network connection, which will be closed automatically when the block finishes.
# (PSEUDOCODE) auth = {:method => :simple, :username => username, :password => password} Net::LDAP.open( :host => ipaddress, :port => 389, :auth => auth ) do |ldap| ldap.search( ... ) ldap.add( ... ) ldap.modify( ... ) end
# File lib/net/ldap.rb, line 466 466: def LDAP::open args 467: ldap1 = LDAP.new args 468: ldap1.open {|ldap| yield ldap } 469: end
Adds a new entry to the remote LDAP server. Supported arguments:
:dn | Full DN of the new entry |
:attributes | Attributes of the new entry. |
The attributes argument is supplied as a Hash keyed by Strings or Symbols giving the attribute name, and mapping to Strings or Arrays of Strings giving the actual attribute values. Observe that most LDAP directories enforce schema constraints on the attributes contained in entries. # will fail with a server-generated error if your attributes violate the server-specific constraints. Here’s an example:
dn = "cn=George Smith,ou=people,dc=example,dc=com" attr = { :cn => "George Smith", :objectclass => ["top", "inetorgperson"], :sn => "Smith", :mail => "gsmith@example.com" } Net::LDAP.open (:host => host) do |ldap| ldap.add( :dn => dn, :attributes => attr ) end
# File lib/net/ldap.rb, line 813 813: def add args 814: if @open_connection 815: @result = @open_connection.add( args ) 816: else 817: @result = 0 818: begin 819: conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption) 820: if (@result = conn.bind( args[:auth] || @auth )) == 0 821: @result = conn.add( args ) 822: end 823: ensure 824: conn.close if conn 825: end 826: end 827: @result == 0 828: end
Add a value to an attribute. Takes the full DN of the entry to modify, the name (Symbol or String) of the attribute, and the value (String or Array). If the attribute does not exist (and there are no schema violations), # will create it with the caller-specified values. If the attribute already exists (and there are no schema violations), the caller-specified values will be added to the values already present.
Returns True or False to indicate whether the operation succeeded or failed, with extended information available by calling #. See also # and #.
dn = "cn=modifyme,dc=example,dc=com" ldap.add_attribute dn, :mail, "newmailaddress@example.com"
# File lib/net/ldap.rb, line 942 942: def add_attribute dn, attribute, value 943: modify :dn => dn, :operations => [[:add, attribute, value]] 944: end
Convenience method to specify authentication credentials to the LDAP server. Currently supports simple authentication requiring a username and password.
Observe that on most LDAP servers, the username is a complete DN. However, with A/D, it’s often possible to give only a user-name rather than a complete DN. In the latter case, beware that many A/D servers are configured to permit anonymous (uncredentialled) binding, and will silently accept your binding as anonymous if you give an unrecognized username. This is not usually what you want. (See #.)
Important: The password argument may be a Proc that returns a string. This makes it possible for you to write client programs that solicit passwords from users or from other data sources without showing them in your code or on command lines.
require 'net/ldap' ldap = Net::LDAP.new ldap.host = server_ip_address ldap.authenticate "cn=Your Username,cn=Users,dc=example,dc=com", "your_psw"
Alternatively (with a password block):
require 'net/ldap' ldap = Net::LDAP.new ldap.host = server_ip_address psw = proc { your_psw_function } ldap.authenticate "cn=Your Username,cn=Users,dc=example,dc=com", psw
# File lib/net/ldap.rb, line 399 399: def authenticate username, password 400: password = password.call if password.respond_to?(:call) 401: @auth = {:method => :simple, :username => username, :password => password} 402: end
# connects to an LDAP server and requests authentication based on the :auth parameter passed to # or #. It takes no parameters.
User code does not need to call # directly. It will be called implicitly by the library whenever you invoke an LDAP operation, such as # or #.
It is useful, however, to call # in your own code when the only operation you intend to perform against the directory is to validate a login credential. # returns true or false to indicate whether the binding was successful. Reasons for failure include malformed or unrecognized usernames and incorrect passwords. Use # to find out what happened in case of failure.
Here’s a typical example using # to authenticate a credential which was (perhaps) solicited from the user of a web site:
require 'net/ldap' ldap = Net::LDAP.new ldap.host = your_server_ip_address ldap.port = 389 ldap.auth your_user_name, your_user_password if ldap.bind # authentication succeeded else # authentication failed p ldap.get_operation_result end
Here’s a more succinct example which does exactly the same thing, but collects all the required parameters into arguments:
require 'net/ldap' ldap = Net::LDAP.new( :host=>your_server_ip_address, :port=>389 ) if ldap.bind( :method=>:simple, :username=>your_user_name, :password=>your_user_password ) # authentication succeeded else # authentication failed p ldap.get_operation_result end
You don’t need to pass a user-password as a String object to bind. You can also pass a Ruby Proc object which returns a string. This will cause bind to execute the Proc (which might then solicit input from a user with console display suppressed). The String value returned from the Proc is used as the password.
You don’t have to create a new instance of Net::LDAP every time you perform a binding in this way. If you prefer, you can cache the Net::LDAP object and re-use it to perform subsequent bindings, provided you call # to specify a new credential before calling #. Otherwise, you’ll just re-authenticate the previous user! (You don’t need to re-set the values of # and #.) As noted in the documentation for #, the password parameter can be a Ruby Proc instead of a String.
# File lib/net/ldap.rb, line 712 712: def bind(auth=@auth) 713: if @open_connection 714: @result = @open_connection.bind auth 715: else 716: begin 717: conn = Connection.new( :host => @host, :port => @port , :encryption => @encryption) 718: @result = conn.bind auth 719: ensure 720: conn.close if conn 721: end 722: end 723: 724: @result == 0 725: end
# is for testing authentication credentials.
As described under #, most LDAP servers require that you supply a complete DN as a binding-credential, along with an authenticator such as a password. But for many applications (such as authenticating users to a Rails application), you often don’t have a full DN to identify the user. You usually get a simple identifier like a username or an email address, along with a password. # allows you to authenticate these user-identifiers.
# is a combination of a search and an LDAP binding. First, it connects and binds to the directory as normal. Then it searches the directory for an entry corresponding to the email address, username, or other string that you supply. If the entry exists, then # will re-bind as that user with the password (or other authenticator) that you supply.
# takes the same parameters as #, with the addition of an authenticator. Currently, this authenticator must be :password. Its value may be either a String, or a proc that returns a String. # returns false on failure. On success, it returns a result set, just as # does. This result set is an Array of objects of type Net::LDAP::Entry. It contains the directory attributes corresponding to the user. (Just test whether the return value is logically true, if you don’t need this additional information.)
Here’s how you would use # to authenticate an email address and password:
require 'net/ldap' user,psw = "joe_user@yourcompany.com", "joes_psw" ldap = Net::LDAP.new ldap.host = "192.168.0.100" ldap.port = 389 ldap.auth "cn=manager,dc=yourcompany,dc=com", "topsecret" result = ldap.bind_as( :base => "dc=yourcompany,dc=com", :filter => "(mail=#{user})", :password => psw ) if result puts "Authenticated #{result.first.dn}" else puts "Authentication FAILED." end
# File lib/net/ldap.rb, line 773 773: def bind_as args={} 774: result = false 775: open {|me| 776: rs = search args 777: if rs and rs.first and dn = rs.first.dn 778: password = args[:password] 779: password = password.call if password.respond_to?(:call) 780: result = rs if bind :method => :simple, :username => dn, :password => password 781: end 782: } 783: result 784: end
Delete an entry from the LDAP directory. Takes a hash of arguments. The only supported argument is :dn, which must give the complete DN of the entry to be deleted. Returns True or False to indicate whether the delete succeeded. Extended status information is available by calling #.
dn = "mail=deleteme@example.com,ou=people,dc=example,dc=com" ldap.delete :dn => dn
# File lib/net/ldap.rb, line 1016 1016: def delete args 1017: if @open_connection 1018: @result = @open_connection.delete( args ) 1019: else 1020: @result = 0 1021: begin 1022: conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption ) 1023: if (@result = conn.bind( args[:auth] || @auth )) == 0 1024: @result = conn.delete( args ) 1025: end 1026: ensure 1027: conn.close 1028: end 1029: end 1030: @result == 0 1031: end
Delete an attribute and all its values. Takes the full DN of the entry to modify, and the name (Symbol or String) of the attribute to delete.
Returns True or False to indicate whether the operation succeeded or failed, with extended information available by calling #. See also # and #.
dn = "cn=modifyme,dc=example,dc=com" ldap.delete_attribute dn, :mail
# File lib/net/ldap.rb, line 976 976: def delete_attribute dn, attribute 977: modify :dn => dn, :operations => [[:delete, attribute, nil]] 978: end
Convenience method to specify encryption characteristics for connections to LDAP servers. Called implicitly by # and #, but may also be called by user code if desired. The single argument is generally a Hash (but see below for convenience alternatives). This implementation is currently a stub, supporting only a few encryption alternatives. As additional capabilities are added, more configuration values will be added here.
Currently, the only supported argument is {:method => :simple_tls}. (Equivalently, you may pass the symbol :simple_tls all by itself, without enclosing it in a Hash.)
The :simple_tls encryption method encrypts all communications with the LDAP server. It completely establishes SSL/TLS encryption with the LDAP server before any LDAP-protocol data is exchanged. There is no plaintext negotiation and no special encryption-request controls are sent to the server. The :simple_tls option is the simplest, easiest way to encrypt communications between Net::LDAP and LDAP servers. It’s intended for cases where you have an implicit level of trust in the authenticity of the LDAP server. No validation of the LDAP server’s SSL certificate is performed. This means that :simple_tls will not produce errors if the LDAP server’s encryption certificate is not signed by a well-known Certification Authority. If you get communications or protocol errors when using this option, check with your LDAP server administrator. Pay particular attention to the TCP port you are connecting to. It’s impossible for an LDAP server to support plaintext LDAP communications and simple TLS connections on the same port. The standard TCP port for unencrypted LDAP connections is 389, but the standard port for simple-TLS encrypted connections is 636. Be sure you are using the correct port.
[Note: a future version of Net::LDAP will support the STARTTLS LDAP control, which will enable encrypted communications on the same TCP port used for unencrypted connections.]
# File lib/net/ldap.rb, line 443 443: def encryption args 444: case args 445: when :simple_tls, :start_tls 446: args = {:method => args} 447: end 448: @encryption = args 449: end
Returns a meaningful result any time after a protocol operation (#, #, #, #, #, #) has completed. It returns an #OpenStruct containing an LDAP result code (0 means success), and a human-readable string.
unless ldap.bind puts "Result: #{ldap.get_operation_result.code}" puts "Message: #{ldap.get_operation_result.message}" end
Certain operations return additional information, accessible through members of the object returned from #. Check #.error_message and #.matched_dn.
# File lib/net/ldap.rb, line 490 490: def get_operation_result 491: os = OpenStruct.new 492: if @result.is_a?(Hash) 493: os.code = (@result[:resultCode] || "").to_i 494: os.error_message = @result[:errorMessage] 495: os.matched_dn = @result[:matchedDN] 496: elsif @result 497: os.code = @result 498: else 499: os.code = 0 500: end 501: os.message = LDAP.result2string( os.code ) 502: os 503: end
Modifies the attribute values of a particular entry on the LDAP directory. Takes a hash with arguments. Supported arguments are:
:dn | (the full DN of the entry whose attributes are to be modified) |
:operations | (the modifications to be performed, detailed next) |
This method returns True or False to indicate whether the operation succeeded or failed, with extended information available by calling #.
Also see #, #, or #, which provide simpler interfaces to this functionality.
The LDAP protocol provides a full and well thought-out set of operations for changing the values of attributes, but they are necessarily somewhat complex and not always intuitive. If these instructions are confusing or incomplete, please send us email or create a bug report on rubyforge.
The :operations parameter to # takes an array of operation-descriptors. Each individual operation is specified in one element of the array, and most LDAP servers will attempt to perform the operations in order.
Each of the operations appearing in the Array must itself be an Array with exactly three elements:
an operator | must be :add, :replace, or :delete |
an attribute name | the attribute name (string or symbol) to modify |
a value | either a string or an array of strings. |
The :add operator will, unsurprisingly, add the specified values to the specified attribute. If the attribute does not already exist, :add will create it. Most LDAP servers will generate an error if you try to add a value that already exists.
:replace will erase the current value(s) for the specified attribute, if there are any, and replace them with the specified value(s).
:delete will remove the specified value(s) from the specified attribute. If you pass nil, an empty string, or an empty array as the value parameter to a :delete operation, the entire attribute will be deleted, along with all of its values.
For example:
dn = "mail=modifyme@example.com,ou=people,dc=example,dc=com" ops = [ [:add, :mail, "aliasaddress@example.com"], [:replace, :mail, ["newaddress@example.com", "newalias@example.com"]], [:delete, :sn, nil] ] ldap.modify :dn => dn, :operations => ops
(This example is contrived since you probably wouldn’t add a mail value right before replacing the whole attribute, but it shows that order of execution matters. Also, many LDAP servers won’t let you delete SN because that would be a schema violation.)
It’s essential to keep in mind that if you specify more than one operation in a call to #, most LDAP servers will attempt to perform all of the operations in the order you gave them. This matters because you may specify operations on the same attribute which must be performed in a certain order.
Most LDAP servers will stop processing your modifications if one of them causes an error on the server (such as a schema-constraint violation). If this happens, you will probably get a result code from the server that reflects only the operation that failed, and you may or may not get extended information that will tell you which one failed. # has no notion of an atomic transaction. If you specify a chain of modifications in one call to #, and one of them fails, the preceding ones will usually not be “rolled back,” resulting in a partial update. This is a limitation of the LDAP protocol, not of Net::LDAP.
The lack of transactional atomicity in LDAP means that you’re usually better off using the convenience methods #, #, and #, which are are wrappers over #. However, certain LDAP servers may provide concurrency semantics, in which the several operations contained in a single # call are not interleaved with other modification-requests received simultaneously by the server. It bears repeating that this concurrency does not imply transactional atomicity, which LDAP does not provide.
# File lib/net/ldap.rb, line 910 910: def modify args 911: if @open_connection 912: @result = @open_connection.modify( args ) 913: else 914: @result = 0 915: begin 916: conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption ) 917: if (@result = conn.bind( args[:auth] || @auth )) == 0 918: @result = conn.modify( args ) 919: end 920: ensure 921: conn.close if conn 922: end 923: end 924: @result == 0 925: end
modify_rdn is an alias for #.
# File lib/net/ldap.rb, line 1001 1001: def modify_rdn args 1002: rename args 1003: end
Opens a network connection to the server and then passes self to the caller-supplied block. The connection is closed when the block completes. Used for executing multiple LDAP operations without requiring a separate network connection (and authentication) for each one. Note: You do not need to log-in or “bind” to the server. This will be done for you automatically. For an even simpler approach, see the class method Net::LDAP#open.
# (PSEUDOCODE) auth = {:method => :simple, :username => username, :password => password} ldap = Net::LDAP.new( :host => ipaddress, :port => 389, :auth => auth ) ldap.open do |ldap| ldap.search( ... ) ldap.add( ... ) ldap.modify( ... ) end
# File lib/net/ldap.rb, line 529 529: def open 530: raise LdapError.new( "open already in progress" ) if @open_connection 531: begin 532: @open_connection = Connection.new( :host => @host, :port => @port, :encryption => @encryption ) 533: @open_connection.bind @auth 534: yield self 535: ensure 536: @open_connection.close if @open_connection 537: @open_connection = nil 538: end 539: end
# File lib/net/ldap.rb, line 1108 1108: def paged_searches_supported? 1109: @server_caps ||= search_root_dse 1110: @server_caps[:supportedcontrol].include?(LdapControls::PagedResults) 1111: end
Rename an entry on the remote DIS by changing the last RDN of its DN. Documentation stub
# File lib/net/ldap.rb, line 983 983: def rename args 984: if @open_connection 985: @result = @open_connection.rename( args ) 986: else 987: @result = 0 988: begin 989: conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption ) 990: if (@result = conn.bind( args[:auth] || @auth )) == 0 991: @result = conn.rename( args ) 992: end 993: ensure 994: conn.close if conn 995: end 996: end 997: @result == 0 998: end
Replace the value of an attribute. # can be thought of as equivalent to calling # followed by #. It takes the full DN of the entry to modify, the name (Symbol or String) of the attribute, and the value (String or Array). If the attribute does not exist, it will be created with the caller-specified value(s). If the attribute does exist, its values will be discarded and replaced with the caller-specified values.
Returns True or False to indicate whether the operation succeeded or failed, with extended information available by calling #. See also # and #.
dn = "cn=modifyme,dc=example,dc=com" ldap.replace_attribute dn, :mail, "newmailaddress@example.com"
# File lib/net/ldap.rb, line 961 961: def replace_attribute dn, attribute, value 962: modify :dn => dn, :operations => [[:replace, attribute, value]] 963: end
Searches the LDAP directory for directory entries. Takes a hash argument with parameters. Supported parameters include:
:base (a string specifying the tree-base for the search);
:filter (an object of type Net::LDAP::Filter, defaults to objectclass=*);
:attributes (a string or array of strings specifying the LDAP attributes to return from the server);
:return_result (a boolean specifying whether to return a result set).
:attributes_only (a boolean flag, defaults false)
:scope (one of: Net::LDAP::SearchScope_BaseObject, Net::LDAP::SearchScope_SingleLevel, Net::LDAP::SearchScope_WholeSubtree. Default is WholeSubtree.)
:size (an integer indicating the maximum number of search entries to return. Default is zero, which signifies no limit.)
# queries the LDAP server and passes each entry to the caller-supplied block, as an object of type Net::LDAP::Entry. If the search returns 1000 entries, the block will be called 1000 times. If the search returns no entries, the block will not be called.
# returns either a result-set or a boolean, depending on the value of the :return_result argument. The default behavior is to return a result set, which is an Array of objects of class Net::LDAP::Entry. If you request a result set and # fails with an error, it will return nil. Call # to get the error information returned by the LDAP server.
When :return_result => false, # will return only a Boolean, to indicate whether the operation succeeded. This can improve performance with very large result sets, because the library can discard each entry from memory after your block processes it.
treebase = "dc=example,dc=com" filter = Net::LDAP::Filter.eq( "mail", "a*.com" ) attrs = ["mail", "cn", "sn", "objectclass"] ldap.search( :base => treebase, :filter => filter, :attributes => attrs, :return_result => false ) do |entry| puts "DN: #{entry.dn}" entry.each do |attr, values| puts ".......#{attr}:" values.each do |value| puts " #{value}" end end end
# File lib/net/ldap.rb, line 619 619: def search args = {} 620: unless args[:ignore_server_caps] 621: args[:paged_searches_supported] = paged_searches_supported? 622: end 623: 624: args[:base] ||= @base 625: result_set = (args and args[:return_result] == false) ? nil : [] 626: 627: if @open_connection 628: @result = @open_connection.search( args ) {|entry| 629: result_set << entry if result_set 630: yield( entry ) if block_given? 631: } 632: else 633: @result = 0 634: begin 635: conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption ) 636: if (@result = conn.bind( args[:auth] || @auth )) == 0 637: @result = conn.search( args ) {|entry| 638: result_set << entry if result_set 639: yield( entry ) if block_given? 640: } 641: end 642: ensure 643: conn.close if conn 644: end 645: end 646: 647: @result == 0 and result_set 648: end
(Experimental, subject to change). Return the rootDSE record from the LDAP server as a Net::LDAP::Entry, or an empty Entry if the server doesn’t return the record.
# File lib/net/ldap.rb, line 1046 1046: def search_root_dse 1047: rs = search( 1048: :ignore_server_caps=>true, 1049: :base=>"", 1050: :scope=>SearchScope_BaseObject, 1051: :attributes=>[:namingContexts,:supportedLdapVersion,:altServer,:supportedControl,:supportedExtension,:supportedFeatures,:supportedSASLMechanisms] 1052: ) 1053: (rs and rs.first) or Entry.new 1054: end
Return the root Subschema record from the LDAP server as a Net::LDAP::Entry, or an empty Entry if the server doesn’t return the record. On success, the Net::LDAP::Entry returned from this call will have the attributes :dn, :objectclasses, and :attributetypes. If there is an error, call # for more information.
ldap = Net::LDAP.new ldap.host = "your.ldap.host" ldap.auth "your-user-dn", "your-psw" subschema_entry = ldap.search_subschema_entry subschema_entry.attributetypes.each do |attrtype| # your code end subschema_entry.objectclasses.each do |attrtype| # your code end
# File lib/net/ldap.rb, line 1080 1080: def search_subschema_entry 1081: rs = search( 1082: :ignore_server_caps=>true, 1083: :base=>"", 1084: :scope=>SearchScope_BaseObject, 1085: :attributes=>[:subschemaSubentry] 1086: ) 1087: return Entry.new unless (rs and rs.first) 1088: subschema_name = rs.first.subschemasubentry 1089: return Entry.new unless (subschema_name and subschema_name.first) 1090: 1091: rs = search( 1092: :ignore_server_caps=>true, 1093: :base=>subschema_name.first, 1094: :scope=>SearchScope_BaseObject, 1095: :filter=>"objectclass=subschema", 1096: :attributes=>[:objectclasses, :attributetypes] 1097: ) 1098: 1099: (rs and rs.first) or Entry.new 1100: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.