require "yaml" require "ldap" include LDAP host = "192.168.1.15" base = "OU=staff,DC=example,DC=com" port = 389 login = "admin" password = "" class ActiveDirectory include LDAP def initialize(options = {}) options.each { |k, v| instance_variable_set(:"@#{k}", v) } end def get_objects connection.search2(@base, LDAP::LDAP_SCOPE_SUBTREE, '(cn=*)',['cn', 'sAMAccountName']) end private def connection return @connection if @connection.instance_of?(LDAP::Conn) || connect end def connect @connection = LDAP::Conn.open(@host, @port) @connection.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3) @connection.bind(@login, @password) end end a = ActiveDirectory.new(:host => host, :base => base, :port => port, :login => login, :password => password) results = a.get_objects users = [] results.each do |r| users << {'login' => r['cn'][0], 'name' => r['sAMAccountName'][0]} end users.each { |u| puts u.to_yaml }