Skip to content

Instantly share code, notes, and snippets.

@alces
Last active January 20, 2023 07:45
Show Gist options
  • Save alces/2e67dbb03f646a7e859c to your computer and use it in GitHub Desktop.
Save alces/2e67dbb03f646a7e859c to your computer and use it in GitHub Desktop.
A groovy script returning a list of users' groups from LDAP server using JNDI API
import javax.naming.directory.*
MYDOM = 'example.com'
// convert DNS domain to a LDAP notation
dns2ldap = {dom ->
'DC=' + dom.split(/\./).join(',DC=')
}
// base OU for our search
GRP_OU = 'OU=users,' + dns2ldap(MYDOM)
/* make a new InitialDirContext for LDAP search
* an awful mess caused only by three not-so-groovy things:
* 1. InitialDirContext's constructor wants Hashtable instead of HashMap as a parameter
* 2. GStrings in the arguments of this constructor should be explicitly converted to java Strings
* 3. groovy's HashMap square brackets constructor doesn't support dots or brackets in keys
*/
mkCtx = {param = [:] ->
new InitialDirContext(
(Hashtable)param.collect {k, v ->
[InitialDirContext[k], v.toString()]
}.collectEntries()
)
}
mkCtx(PROVIDER_URL: "ldap://ldap.$MYDOM",
INITIAL_CONTEXT_FACTORY: 'com.sun.jndi.ldap.LdapCtxFactory',
SECURITY_AUTHENTICATION: 'simple',
SECURITY_PRINCIPAL: "CN=dummy,$GRP_OU",
SECURITY_CREDENTIALS: 'aTerriblyStup1dPassW0rd',
).search(
GRP_OU, '(objectclass=group)', new SearchControls([searchScope: SearchControls.SUBTREE_SCOPE])
).collect {
it.attributes['cn']
}.sort().join('\n')
@davkar3n
Copy link

davkar3n commented Jan 20, 2023

def response = (
mkCtx(PROVIDER_URL: "ldap://ldap.$MYDOM",
INITIAL_CONTEXT_FACTORY: 'com.sun.jndi.ldap.LdapCtxFactory',
SECURITY_AUTHENTICATION: 'simple',
SECURITY_PRINCIPAL: "yourAdminUser",
SECURITY_CREDENTIALS: 'YourAdminUserPassword',
).search(
GRP_OU, '(objectclass=group)', new SearchControls([searchScope: SearchControls.SUBTREE_SCOPE])
).collect {
it.attributes['cn']
}
)
return response.sort().join('\n')

def group_list = []

for(i = 0; i < response.size(); i++){
response[i] = response[i].toString().replaceAll("cn:", "")
group_list.add(response[i])
}
server_list = group_list.unique()
return group_list.sort()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment