准备工作
安装需要用到的gem
gem install net-ldap
gem install roo
准备好要更新的数据,比如exel表: /root/account.xlsx,内容如下
姓名 | 性别 |
张三 | 男 |
李四 | 女 |
实现代码
require 'roo'
require 'net/ldap'
xlsx = Roo::Excelx.new("../account.xlsx")
ary = Array.new
#这里如果excel中的标签不是Sheet1,需要修改
xlsx.sheet_for("Sheet1").each_row do |row|
ary << row.map(&:cell_value).reverse
end users = ary.to_h if ARGV.count == 2
ldap = Net::LDAP.new :host => "172.16.1.6",
:port => 389,
:auth => {
:method => :simple,
:username => ARGV.first,
:password => ARGV.last
} count, rules = 0, []
treebase = "OU=User,OU=ABC,DC=example,DC=com"
ldap.search(:base => treebase, :scope => Net::LDAP::SearchScope_SingleLevel) do |entry|
displayname = entry.displayname.shift unless displayname.nil?
puts "########################################"
if users.has_key?(displayname)
ldap.modify :dn => entry.dn, :operations => [[ :replace, :pager, users.fetch(displayname) ]]
rules.delete(displayname) ; count += 1
puts "名字:#{displayname},性别:#{users.fetch(displayname)}: 已更新"
else
puts "跳过【#{displayname}】"
end
end
end
puts "更新总人数:#{count}"
#输出AD中未找到的用户
rules.each do |key, value|
puts "#{key}, #{value}"
end
end
至此,Excel表中的数据就更新到AD对应的属性了。