Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Reading Microsoft AD users via python

Posted on 2008-09-30
Medium Priority
Last Modified: 2013-12-05
I have the following script in python, that reads user properties from Microsoft Active Directory. However I have some basic issues regarding string manipulation with this tool.
Basically, I try to read:
username, first name, last name
and then feed this result to a shell command in my linux system.
however I cannot properly handle the following situations:
a- first name field is blank
b- first name field contains spaces example "Erick Perez"
c- same for last name field (a and b)
d- last name or first name contains numbers, tildes or the letter ñ. (ASCII 0164)

Please advice.

# Notes:
# This script automatically creates zimbra accounts from active directory.
# The user must be enabled, otherwise it will be skipped.
# Variables can be changed here:
import ldap, string, os, time, sys 
# BaseDN to search for user accounts.
base = 'cn=users,dc=quadrian,dc=gob,dc=pa'
scope = ldap.SCOPE_SUBTREE
# We filter for user accounts only, we skip machine and groups
filter = "(&(objectclass=person) (uid=%s))"
# Active Directory Domain Name
domain = "" 
# Active Directory Domain Controller
#ldap port usually 389
# Email domain to be used in mail applications
# Bind Domain for LDAP user account that will query the AD
#the account name of the account to bind to ldap and query de AD
# Here We list all Zimbra Accounts. So we can compare if the account we read from AD
# is already created in Zimbra or not.
f = os.popen(pathtozmprov +' gaa')
zmprovgaa= []
zmprovgaa = f.readlines()
# Here we initialize the LDAP connection 
	print "Your username or password to bind to LDAP is incorrect."
except ldap.LDAPError, e:
	if type(e.message) == dict and e.message.has_key('desc'):
		print e.message['desc']
		print e
# End of LDAP initialization
# Now we look for ENABLED user accounts in AD and get the following values
# sAMAccountName is the username to log on to the domain
# givenName is the first name
# sn is the surname or last name
# example of current usernames in the domain
# 4-982-345
# ericklatam
# memberOf are the groups this user belongs to
    res = l.search_s(base,scope, "(&(ObjectCategory=user)  (userAccountControl=512))",  ['sAMAccountName','givenName','sn','memberOf'])
#userAccountControl  512 = normal , 514 = disabled account
    for (dn, vals) in res:
      accountname = vals['sAMAccountName'][0].lower()
      print "accountname: "+accountname
        sirname = vals['sn'][0].lower()
        sirname = vals['sAMAccountName'][0].lower()
        givenname = vals['givenName'][0]
        givenname = vals['sAMAccountName'][0].lower()
        groups = vals['memberOf']
        groups = 'none'
      initial = givenname[:1].upper()
      sirname = sirname.replace(' ', )
      sirname = sirname.replace('\\', )
      sirname = sirname.replace('-', )
      sirname = sirname.capitalize()
      name = initial + "." + sirname
      accountname = accountname + "@" + emaildomain
      password = "  \'\' "
      # if the account doesn't exist in the output of zmprov gaa create the  account
      if accountname +"\n" not in zmprovgaa:
        print  accountname," exists in active directory but not in zimbra, the   account is being created\n"
        os.system(pathtozmprov +' ca %s %s displayName %s' %  (accountname,password,name))

Open in new window

Question by:erickperez
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
LVL 29

Accepted Solution

pepr earned 2000 total points
ID: 22618544
Well, I do not know the ldap module. For the string module, you usually do not need it as the majority of its functionality was replaced by the built-in string methods.

For the ability to work correctly with the non-ASCII characters (above 127), Python is able to work in the "native" encoding of the OS or with UNICODE. It depends in what form you get the string. Try

print repr(myStringVariable) and you will see u'some string' or without u -- 'some string'. When working with 8-bit encoding, you have to tell Python what 8-bit encoding you use.

Please, show some examples of the problematic names (with spaces, none,...). Point to the lines in your code where you observe the problems.


Author Comment

ID: 23043354
sorry, been traveling.
i will repost with exmaples.
LVL 29

Expert Comment

ID: 23242252
Well, did you solved the problem with my hints? Or why you accepted it?

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Installing Python 2.7.3 version on Windows operating system For installing Python first we need to download Python's latest version from URL" " You can also get information on Python scripting language from the above mentioned we…
Background Information Recently I have fixed file server permission issues for one of my client. The client has 1800 users and one Windows Server 2008 R2 domain joined file server with 12 TB of data, 250+ shared folders and the folder structure i…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question