A few examples on accessing AD in Ruby. Sorry, but I forgot where I grabbed it.
require 'rubygems'
require "iconv"
require 'net/ldap'
class ManageUsers
def initialize
@ldap = Net::LDAP.new
@ldap.host = "#{server ip address}"
@ldap.port = 636
@ldap.encryption :simple_tls
@ldap.auth "cn=#{a domain admin},cn=Users,dc=example,dc=com", "#{A domain admin pass}"
end
#encodes the password
def ct2uni(pwd)
unicodepwd = Iconv.conv('UTF-16LE', 'UTF-8', '"'+pwd+'"')
unicodepwd
end
#cn is case sensative and must look similar to this example Yui Makino
def create(cn)
#this takes a first and last name and turns them into a username, e.g. Yui Makino => ymakino
firstname = cn[/([A-Za-z]*)/]
lastname = cn[/ [a-zA-Z]*/]
username = firstname.gsub(/[a-z]*/, "").downcase + lastname.gsub(/ /,"").downcase
md5_pass = Digest::MD5.hexdigest(username)[0..5]
dn = "cn=#{cn},cn=Users,dc=example,dc=com"
attr = {
:cn => "#{cn}",
:objectclass => "user",
:displayname => "#{cn}",
:sn=> lastname,
:givenname => firstname,
:samaccountname => "#{username}",
:userprincipalname => "#{username}@example.com",
:mail => "#{username}@example.com"
}
results = {}
@ldap.add :dn => dn, :attributes => attr
results[0] = @ldap.get_operation_result
#Passwords cannot be set when creating a user, when using ldap. You can, however, change the password of a created account. Thus, here we have created the account then are coming back to set the password. The password must be in double quotes then encoded into Unicode, UTF-16LD, the ct2uni function handles all of this for us.
@ldap.replace_attribute dn, :unicodepwd, ct2uni(md5_pass)
results[1] = @ldap.get_operation_result
results[2] = @ldap.replace_attribute dn, :useraccountcontrol, "512"
results
end
def delete(user)
dn = "cn=#{user},cn=Users,dc=example,dc=com"
@ldap.delete :dn => dn
return @ldap.get_operation_result
end
end