Fetching information from Active Directory using Python
Here are two simple scripts written in Python to fetch information about users from Active Directory. The AD schema has been augmented with the Microsoft Services For Unix schema, which will allow to map Unix uids to Windows user accounts.
All you need to do is to fill in your own domain controller, AD distinguished name (user account) and the password for it in /etc/ad.secret. You shoud use a less privileged account than Administrator for security. Also remember to set the permissions for ad.secret so that only privileged users have access.
This one will fetch the real name of a user when given a Unix uid:
#!/usr/bin/python
import sys
import ldap
if len(sys.argv) < 2:
print "usage: getrealname <username>"
sys.exit()
Server = "dc1.koo.fi"
DN = "cn=Administrator,cn=Users,dc=koo,dc=fi"
Secret = file("/etc/ad.secret").readline().strip()
Base = "dc=koo,dc=fi"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(msSFU30Name="+sys.argv[1]+"))"
Attrs = ["displayName", "msSFU30Name"]
l = ldap.open(Server)
l.simple_bind(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
And this one will do the same for e-mail:
#!/usr/bin/python
import sys
import ldap
if len(sys.argv) < 2:
print "usage: getemail <username>"
sys.exit()
Server = "dc1.koo.fi"
DN = "cn=Administrator,cn=Users,dc=koo,dc=fi"
Secret = file("/etc/ad.secret").readline().strip()
Base = "dc=koo,dc=fi"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(msSFU30Name="+sys.argv[1]+"))"
Attrs = ["mail", "msSFU30Name"]
l = ldap.open(Server)
l.simple_bind(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('mail'):
mail = Attrs['mail'][0]
print mail
sys.exit()