Created
August 11, 2011 14:31
-
-
Save roy/1139792 to your computer and use it in GitHub Desktop.
Active Directory searching with ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'net/ldap' | |
class ActiveDirectory | |
#server has to be full name.domain.com | |
#treebase is dc=domain,dc=com | |
def initialize(username, password, server, treebase) | |
@username, @password, @server, @treebase = username, password, server, treebase | |
@ldap_con = Net::LDAP.new({ | |
:host => @server, | |
:port => 389, | |
:auth => { | |
:method => :simple, | |
:username => @username, | |
:password => @password | |
} | |
}) | |
end | |
def cleanup_members(members) | |
members.map {|m| m[/^\w{2}=(.*?),/, 1] } | |
end | |
def get_mail(username) | |
op_filter = Net::LDAP::Filter.eq( "samaccountname", username ) | |
entries = @ldap_con.search({ | |
:base => @treebase, | |
:filter => op_filter, | |
:attributes => ['samaccountname','mail'] | |
}) | |
entries[0].mail | |
end | |
def get_members(username) | |
op_filter = Net::LDAP::Filter.eq( "samaccountname", username ) | |
entries = @ldap_con.search({ | |
:base => @treebase, | |
:filter => op_filter, | |
:attributes=> ['samaccountname','memberof'] | |
}) | |
entry = entries[0] | |
return [] if entry.nil? | |
cleanup_members( entry.memberof ) | |
end | |
def member_of?(username, group) | |
get_members(username).include?( group ) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ad = ActiveDirectory.new('user','password','host','dc=domain,dc=com') | |
pp ad.get_mail('someuser') | |
pp ad.get_members("someuser") | |
if ad.member_of? "someuser", "administrators" | |
puts "YES We can do work" | |
end | |
Credits go to Glenn West: http://mentalpagingspace.blogspot.com/2008/12/ruby-on-rails-are-you-member.html | |
This is just a more rubyish implementation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment