DirectoryServices to Dictionary
From IronPython Cookbook
This is a very simple helper function that converts a DirectoryServices object to a more familiar python dictionary.
import sys,System,clr
clr.AddReference("System.DirectoryServices")
def get_ldap_path():
'''get a hopefully useful root ldap path'''
root = System.DirectoryServices.DirectoryEntry()
for prop in root.Properties:
if prop.PropertyName=='distinguishedName':
return prop.Value
def ad2dict(short_path='',full_path='',):
ad_dict={}
if short_path and not full_path:
prefix='LDAP://'
suffix=get_ldap_path()
full_path=prefix+short_path+suffix
print 'making dictionary for',full_path
adobj = System.DirectoryServices.DirectoryEntry(full_path)
for i in adobj.Properties: ad_dict[i.PropertyName]=i.Value
return ad_dict
#specify a relative path
user='cn=fred,OU=Slate,'
print ad2dict(user)
#or specify a full path
full_path='LDAP://cn=fred,OU=Slate,DC=Rubble,DC=Bedrock'
print ad2dict(full_path=full_path)
Back to Contents.

