Welcome, guest | Sign In | My Account | Store | Cart

From Active Directory (or any other LDAP server) dump ALL information about computers, users, and groups, in a nicely formatted report.

Python, 299 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
from win32com.client import (
    GetObject,
    Dispatch,
    )

from pythoncom import (
    com_error,
    )

import datetime

import re

from textwrap import fill

# --------- #

__test__ = {}

# --------- #

# 12/30/1899, the zero-Date for ADO = 693594
_ADO_zeroHour = datetime.date(1899, 12, 30).toordinal()

_time_zero = datetime.time(0, 0, 0)

def ADO_PyTime_To_Datetime(v):
    
    v_date, v_time = divmod(float(v), 1)
    datetime_date = datetime.date.fromordinal(
        int(round(v_date + _ADO_zeroHour)))
    v_time = int(round(86400 * v_time))
    v_hour, v_min = divmod(v_time, 3600)
    v_min, v_sec = divmod(v_min, 60)
    datetime_time = datetime.time(
        int(v_hour), int(v_min), int(v_sec))
    return (datetime_date, datetime_time)

# --------- #

class SentinalSingleton(object):
    def __str__(self):
        return self.__class__.__name__
    __repr__ = __str__

class UntranslatableCOM(SentinalSingleton):
    pass 

UntranslatableCOM = UntranslatableCOM()

class UnrecognizedCOM(SentinalSingleton):
    pass

UnrecognizedCOM = UnrecognizedCOM()

re_read_write_buffer = re.compile(
    r'^\<read-write buffer '
     'ptr 0x([0-9A-F]+)\, '
     'size ([0-9A-F]+) '
     'at 0x([0-9A-F]+)\>$')

__test__['re_read_write_buffer'] = r'''

    >>> bool(re_read_write_buffer.match(
    ...     '<read-write buffer ptr 0x00A4DF40, size 28 at 0x00A4DF20>'))
    True
    
'''

def _process_COM_value(V):
    """
    
    >>> _process_COM_value(3)
    3
    >>> _process_COM_value((3, 3, 3))
    [3, 3, 3]
    >>> _process_COM_value((UntranslatableCOM, UntranslatableCOM))
    UntranslatableCOM
    >>> _process_COM_value((UntranslatableCOM, 3))
    [UntranslatableCOM, 3]
    >>> _process_COM_value((UntranslatableCOM, UnrecognizedCOM))
    [UntranslatableCOM, UnrecognizedCOM]
    
    """
    
    if V in [UntranslatableCOM, UnrecognizedCOM, None]:
        
        return V
    
    elif isinstance(
        V,
        (
            str,
            float,
            int,
            long,
            datetime.date,
            datetime.time,
            datetime.datetime,
            )):
        
        return V
        
    elif isinstance(V, unicode):
        
        try:
            return V.encode('latin-1')
        except UnicodeEncodeError:
            return V
        
    elif isinstance(V, (tuple, list)):
        L = map(_process_COM_value, V)
        if L == ([UntranslatableCOM] * len(L)):
            return UntranslatableCOM
        else:
            return L
        
    elif type(V).__name__ == 'time':
        
        d, t = ADO_PyTime_To_Datetime(V)
        if t == _time_zero:
            return d
        else:
            return datetime.datetime.combine(d, t)
        
    else:
        
        R = repr(V)
    
        if R == '<COMObject <unknown>>':
            
            return UntranslatableCOM
        
        elif re_read_write_buffer.match(R):
            
            return UntranslatableCOM
        
        else:
            
            return UnrecognizedCOM
            
            #for S in ['V', 'type(V)', 'str(V)', 'repr(V)', 'type(V).__name__']:
            #    print '%s: %r' % (S, eval(S))
            #
            #raise ValueError, V

# --------- #

class LDAP_COM_Wrapper(object):

    def __init__(self, LDAP_COM_Object):
        
        self.__dict__[None] = LDAP_COM_Object

    def __getattr__(self, name):
        
        LDAP_COM_Object = self.__dict__[None]
        
        try:
            V = LDAP_COM_Object.Get(name)
        except com_error:
            pass
        else:
            return _process_COM_value(V)
        
        try:
            V = getattr(LDAP_COM_Object, name)
        except (AttributeError, com_error):
            pass
        else:
            return _process_COM_value(V)
        
        raise AttributeError
    
    def __getitem__(self, name):
        
        _getattr = self.__getattr__
        
        try:
            return _getattr(name)
        except AttributeError:
            raise KeyError

def LDAP_COM_to_dict(X):
    
    d = {}
    for i in range(X.PropertyCount):
        P = X.Item(i)
        Name = P.Name
        d[Name] = _process_COM_value(X.Get(Name))
    return d
        
def LDAP_select_all_iterator(Connection, LDAP_query_string):

    R = Connection.Execute(LDAP_query_string)[0]

    while not R.EOF:
        
        d = {}
        for f in R.Fields:
            d[f.Name] = _process_COM_value(f.Value)
        yield d
    
        R.MoveNext()
        
def LDAP_select_then_ADsPath_iterator(Connection, LDAP_query_string):
    
    for r in LDAP_select_all_iterator(Connection, LDAP_query_string):
    
        X = GetObject(r['ADsPath'])
        X.GetInfo()
        
        yield LDAP_COM_to_dict(X)
        
# --------- #

def _sort_helper(d):
    s = d.get('name', '<<<MISSING>>>')
    try:
        s = str(s)
    except UnicodeEncodeError:
        s = repr(s)
    return s.lower()

def _get_all_of_objectClass(
    Connection, defaultNamingContext, objectClass):
    
    LDAP_query_string = (
        "Select * "
        "from 'LDAP://%s' "
        "where objectClass = '%s'" % (
            defaultNamingContext,
            objectClass,
            ))
    
    print 'LDAP_query_string: %r' % (LDAP_query_string,)
    
    L = list(LDAP_select_then_ADsPath_iterator(
        Connection, LDAP_query_string))
    
    L.sort(key=_sort_helper)

    for d in L:
        
        print '\n'
        for k in ['name', 'description']:
            v = d.get(k, '<<<MISSING>>>')
            print fill(
                '%s: %s' % (k, v),
                width=70,
                initial_indent='',
                subsequent_indent='    ',
                )
        
        for k in sorted(d.keys()):
            try:
                k = str(k)
            except UnicodeEncodeError:
                continue
            v = d[k]
            if v is UntranslatableCOM:
                continue
            try:
                v = str(v)
            except UnicodeEncodeError:
                v = repr(v)
            print fill(
                '%s: %s' % (k, v),
                width=70,
                initial_indent='    ',
                subsequent_indent='        ',
                )
            
def main():
    
    Connection = Dispatch("ADODB.Connection")
    
    Connection.Open("Provider=ADSDSOObject")
    
    defaultNamingContext = LDAP_COM_Wrapper(
        GetObject('LDAP://rootDSE'))['defaultNamingContext']
        
    print 'defaultNamingContext: %r' % (defaultNamingContext,)
    
    for objectClass in ['computer', 'user', 'group']:
        
        print
        
        try:
            _get_all_of_objectClass(
                Connection, defaultNamingContext, objectClass)
        except com_error:
            print (
                '<<<REPORT FAILED FOR: objectClass %s>>>' % (
                    objectClass,))
        
if __name__ == '__main__':

    main()
                     

(Uses Mark Hammond's Python for Windows extensions (pywin32))

I am glad I wrote this, now I can dump all information about our Windows network into a readable text file, information about servers, workstations, users, and security groups.

Big improvement since my last LDAP scripting coding attempt. This code does a pretty good job of grabbing LDAP info (via Windows/Python COM automation) and turning it into Python dicts.

Converts COM dates and times to Python 'datetime' objects, and otherwise returns objects and values directly usable by Python.

This is much more sophisticated than any other LDAP scripting code I have ever seen on the Internet, in that it programmically discovers all the attributes for each data record, which is a big help when you don't know the exact name of the attribute.

Also a good example of:

* programmically finding out your defaultNamingContext

* using ADsPath to retrieve the data

* remotely connecting to the Active Directory server (not all code examples use the 'GetInfo' method needed to access data remotely)

* converting Windows COM/ADO dates and times into Python datetime objects

Frankly, this type of work is usually done with VBScript, but all the VBScript examples I have ever read (dozens) are of pathetically low quality. This is an example of robustly scripting with LDAP, and programmically discovering all information stored. IMO, the Perl LDAP scripting examples I have seen are pretty weak as well, in these regards.

It is mindboggling how much better Python (with pywin32) is at Windows scripting than VBScript. I shudder to think how many hundreds of lines longer the VBScript code would be, with much less functionality, and much less polish, and much less robustness.

5 comments

kurt schwehr 14 years, 7 months ago  # | flag

How about on other OSes? For those of us on Mac and Linux boxes, how might we access this Active Directory that all our coworkers keep talking about?

Mark Mc Mahon 14 years, 7 months ago  # | flag

PyTime conversion... Hi,

I have found that

converted = datetime.fromtimestamp(int(time))

works well for converting from PyTime to Datetime.

Manuel Garcia (author) 14 years, 7 months ago  # | flag

int(pytime) instead of float(pytime). I cannot report good results with int(pytime). With "real-world" data, there are just too many garbage dates inside of Active Directory. "int(pytime)" raised a ValueError, but doing it the "hard way" with "float(pytime)" does not raise an exception.

But, granted, the dates that raise ValueError with "int(pytime)" are probably not worth trying to view as dates.

Vicente Soler 11 years, 3 months ago  # | flag

I'am using Python 3.1

I've converted your script to V3.1 by means of script 2to3 and still does not work because converted file needs to be further manually amended.

Is it possible that you post a 3.1 enabled script?

Thank you

Dev 6 years, 1 month ago  # | flag

This script works perfect. How can we import all output data in CSV or JSON file here? Please comment