title: Jython LDAP script to retrieve sAMAccountName attribute value
body: <p>I need to create a jython script to retrieve the sAMAccountName attribute from Active Directory and either store it in a database table and/or evaluate it against existing data. The purpose is to evaluate if a user has been removed from a group in AD and set that user as inactive in Maximo. The script will returned account names and set the Maximo user as inactive for those Maximo users not returned by the LDAP query. Maximo does not delete or otherwise modify a user when a user has been removed from the AD. Here is the code thus far i found from an example.</p>
  
  <pre><code># Jython LDAP Example
  
  from javax.naming import *
  from java.util import *
  from javax.naming.directory import *
  
  # Credentials to access LDAP
  user = "cn=binduser,dc=domain,dc=com"
  passwd = "password"
  
  # Query starting point and query target 
  search_start = "dc=domain,dc=com"
  search_target = "(&amp;(objectClass=user)(memberof=CN=Maximo,OU=Groups,DC=domain,DC=com))"
  #search_attributes = "sAMAccountName"
  
  # Setup LDAP Context Options
  settings = Hashtable()
  settings.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory")
  settings.put(Context.PROVIDER_URL, "ldap://ldapserver:389")
  settings.put(Context.SECURITY_PRINCIPAL, user)
  settings.put(Context.SECURITY_CREDENTIALS, passwd)
  
  # Connect to LDAP Server
  ctx = InitialDirContext(settings)
  
  srch = SearchControls()
  srch.setSearchScope(SearchControls.SUBTREE_SCOPE)
  
  # Execute LDAP Search
  results = ctx.search(search_start, search_target, srch )
  
  #Display Search`
  for result in results:
  
      attributes = result.getAttributes()
      names = []
      for atr in attributes.getIDs():
          if atr == "sAMAccountName":
              names.append(str(atr))
  
      for name in names:
          print attributes.get(name)
  </code></pre>
  
  <p>This however produces the result: "sAMAccountName: userid".</p>
  
  <p>How can i tell it to only search or return the value of the sAMAccountName and not all the other attributes? Right now this script returns all the attributes associated with the user which is not required, only the sAMAccountName is needed. </p>
  
  <p>The first part is retrieving just the account names from LDAP which i am unfamiliar with.</p>
  
  <p>Thanks!</p>