Ruby/LDAP を使って LDAP からユーザーとその所属グループのリストを生成する

February 6, 2008

Ruby/LDAP を使う。Ruby/LDAP

  1. People からユーザとそのメイングループ番号を gidNumber から取得する。
  2. 各ユーザーのメイングループの cn を取得する。
  3. グループを全て走査して、所属するユーザーにマップをグループに追加する。
  4. 「user:group1,group2」という形式で書き出す。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env ruby
require 'ldap'
people = Hash.new
LDAP::SSLConn.new("ldap.company.com") do |conn|
conn.set_option(LDAP::LDAP\_OPT\_PROTOCOL_VERSION,3)
bind_conn = conn.bind(バインドユーザのDN, バインドユーザのパスワード)
bind_conn.search2("ou=People,dc=company,dc=com",
LDAP::LDAP\_SCOPE\_SUBTREE,
"uidNumber=*", \['uid', 'gidNumber'\]) { |entry|
uid = entry\['uid'\].first
gid = entry\['gidNumber'\].first
people.store(uid, gid)
}
people.each do |k, v|
bind_conn.search2("ou=Group,dc=company,dc=com",
LDAP::LDAP\_SCOPE\_SUBTREE,
"gidNumber=#{v}", \['cn'\]) { |entry|
cn = entry\['cn'\].first
people.store(k, \[cn\])
}
end
groups = Array.new
bind_conn.search2("ou=Group,dc=company,dc=com",
LDAP::LDAP\_SCOPE\_SUBTREE,
"gidNumber=*", \['dn'\]) { |entry|
entry\['dn'\].each { |e|
groups.push e
}
}
groups.each do |group|
bind_conn.search2(group,
LDAP::LDAP\_SCOPE\_SUBTREE,
"(objectClass=*)", \['cn', 'memberUid'\]) { |entry|
cn = entry\['cn'\].first
uids = entry\['memberUid'\]
next if uids.nil?
uids = \[uids\] unless uids.is_a?(Array)
uids.each { |uid|
if people.key? uid
people\[uid\].push(cn)
end
}
}
end
end
people.each do |uid, groups|
print "#{uid}:"
puts groups.join(",")
end

tilfin freelance software engineer