Solved

Reading Microsoft AD users via python

Posted on 2008-09-30
3
822 Views
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.

#!/usr/bin/python
 

#--------------------------------------------------------------------------------------------------

# 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 = "quadrian.gob.pa" 

# Active Directory Domain Controller

ldapserver="ancon"

#ldap port usually 389

port="389"

# Email domain to be used in mail applications

emaildomain="quadrian.gob.pa"

# Bind Domain for LDAP user account that will query the AD

ldapbinddomain="organojudicial"

#the account name of the account to bind to ldap and query de AD

ldapbind="zimbrasync"

ldappassword="xxxxxxx"

pathtozmprov="/opt/zimbra/bin/zmprov"

#--------------------------------------------------------------------------------------------------

# 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 

l=ldap.initialize("ldap://"+ldapserver+"."+domain+":"+port)

try:

	l.simple_bind_s(ldapbinddomain+"\\"+ldapbind,ldappassword)

except ldap.INVALID_CREDENTIALS:

	print "Your username or password to bind to LDAP is incorrect."

	sys.exit()

except ldap.LDAPError, e:

	if type(e.message) == dict and e.message.has_key('desc'):

		print e.message['desc']

	else:

		print e

	sys.exit()

# 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
 

try:

    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

      try:

        sirname = vals['sn'][0].lower()

      except:

        sirname = vals['sAMAccountName'][0].lower()

      try:

        givenname = vals['givenName'][0]

      except:

        givenname = vals['sAMAccountName'][0].lower()

      try:

        groups = vals['memberOf']

      except:

        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 = "  \'\' "

      sys.stdout.flush()

      # 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"

        time.sleep(1)

        os.system(pathtozmprov +' ca %s %s displayName %s' %  (accountname,password,name))

             

l.unbind_s()

Open in new window

0
Comment
Question by:erickperez
  • 2
3 Comments
 
LVL 28

Accepted Solution

by:
pepr earned 500 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.



0
 

Author Comment

by:erickperez
ID: 23043354
sorry, been traveling.
i will repost with exmaples.
0
 
LVL 28

Expert Comment

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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Python 2.7 - Save to file 4 51
Windows Update not working 12 114
Turning python script into an applet 12 102
Downgrading from Python 3.4.5 to 3.4.3 5 19
Remote Apps is a feature in server 2008 which allows users to run applications off Remote Desktop Servers without having to log into them to run the applications.  The user can either have a desktop shortcut installed or go through the web portal to…
Installing Python 2.7.3 version on Windows operating system For installing Python first we need to download Python's latest version from URL" www.python.org " You can also get information on Python scripting language from the above mentioned we…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…

911 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now