Groovy script to access and modify LDAP or Active Directory using groovy ldap library.
Need following library:
groovy-ldap.jar
Class loading:
this.getClass().classLoader.rootLoader.addURL(new File("lib/groovy-ldap.jar").toURL());
import org.apache.directory.groovyldap.*;
Connecting LDAP:
LDAP = Class.forName("org.apache.directory.groovyldap.LDAP");
SearchScope = Class.forName("org.apache.directory.groovyldap.SearchScope");
host = "<ldap_host_addr>";
ad_user = "<ldap_priv_userid>";
ad_password = "<password>";
ldap = LDAP.newInstance(host, ad_user, ad_password);
println "Connected to AD => $host";
Reading an entry:
search_str = "uid=<uid_info>*"; //* regex match
entries = ldap.search(search_str, "<ldap_ou_path>", SearchScope.ONE);
print "${entries.size} entries are found\n\n";
for (entry in entries) {
print """
DN: ${entry.dn}
Common name: ${entry.cn}
uid: ${entry.uid}
Object classes: ${entry.objectclass}
"""
}
Modify an entry:
//user dn is needed; it wont modify cn
dn = "<dn_of_entry_to_be_modified>";
mods = [
["REPLACE", [<field_name_1>: "<new_value_1>"]],
["REPLACE", [<field_name_2>: "<new_value_2>"]],
["ADD", [<new_field>: "<new_value>"]]
]
ldap.modify(dn, mods);
print "LDAP entry modified\n";