home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_win32comext_adsi_test.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  7.3 KB  |  247 lines

  1. import sys, string
  2. import pythoncom
  3.  
  4. import win32api
  5. from win32com.adsi import *
  6.  
  7. verbose_level = 0
  8.  
  9. server = '' # Must have trailing /
  10. local_name = win32api.GetComputerName()
  11.  
  12. def DumpRoot():
  13.     "Dumps the root DSE"
  14.     path = "LDAP://%srootDSE" % server
  15.     rootdse = ADsGetObject(path)
  16.  
  17.     for item in rootdse.Get("SupportedLDAPVersion"):
  18.         print "%s supports ldap version %s" % (path, item)
  19.     
  20.     attributes = ["CurrentTime", "defaultNamingContext"]
  21.     for attr in attributes:
  22.         val = rootdse.Get(attr)
  23.         print " %s=%s" % (attr, val)
  24.  
  25. ###############################################
  26. #
  27. # Code taken from article titled:
  28. # Reading attributeSchema and classSchema Objects
  29. def _DumpClass(child):
  30.     attrs = "Abstract lDAPDisplayName schemaIDGUID schemaNamingContext attributeSyntax oMSyntax"
  31.     _DumpTheseAttributes(child, string.split(attrs))
  32.     
  33. def _DumpAttribute(child):
  34.     attrs = "lDAPDisplayName schemaIDGUID adminDescription adminDisplayName rDNAttID defaultHidingValue defaultObjectCategory systemOnly defaultSecurityDescriptor"
  35.     _DumpTheseAttributes(child, string.split(attrs))
  36.  
  37. def _DumpTheseAttributes(child, attrs):
  38.     for attr in attrs:
  39.         try:
  40.             val = child.Get(attr)
  41.         except pythoncom.com_error, details:
  42.             continue
  43.             # ###
  44.             (hr, msg, exc, arg) = details
  45.             if exc and exc[2]: msg = exc[2]
  46.             val = "<Error: %s>" % (msg,)
  47.         if verbose_level >= 2:
  48.             print " %s: %s=%s" % (child.Class, attr, val)
  49.  
  50. def DumpSchema():
  51.     "Dumps the default DSE schema"
  52.     # Bind to rootDSE to get the schemaNamingContext property.
  53.     path = "LDAP://%srootDSE" % server
  54.     rootdse = ADsGetObject(path)
  55.     name = rootdse.Get("schemaNamingContext")
  56.     
  57.     # Bind to the actual schema container.
  58.     path= "LDAP://" + server + name
  59.     print "Binding to", path
  60.     ob = ADsGetObject(path)
  61.     nclasses = nattr = nsub = nunk = 0
  62.  
  63.     # Enumerate the attribute and class objects in the schema container.
  64.     for child in ob:
  65.         # Find out if this is a class, attribute, or subSchema object.
  66.         class_name = child.Class
  67.         if class_name == "classSchema":
  68.             _DumpClass(child)
  69.             nclasses = nclasses + 1
  70.         elif class_name == "attributeSchema":
  71.             _DumpAttribute(child)
  72.             nattr = nattr + 1
  73.         elif class_name == "subSchema":
  74.             nsub = nsub + 1
  75.         else:
  76.             print "Unknown class:", class_name
  77.             nunk = nunk + 1
  78.     if verbose_level:
  79.         print "Processed", nclasses, "classes"
  80.         print "Processed", nattr, "attributes"
  81.         print "Processed", nsub, "sub-schema's"
  82.         print "Processed", nunk, "unknown types"
  83.  
  84. def _DumpObject(ob, level = 0):
  85.     prefix = "  " * level
  86.     print "%s%s object: %s" % (prefix, ob.Class, ob.Name)
  87.     # Do the directory object thing
  88.     try:
  89.         dir_ob = ADsGetObject(ob.ADsPath, IID_IDirectoryObject)
  90.     except pythoncom.com_error:
  91.         dir_ob = None
  92.     if dir_ob is not None:
  93.         info = dir_ob.GetObjectInformation()
  94.         print "%s RDN='%s', ObjectDN='%s'" % (prefix, info.RDN, info.ObjectDN)
  95.         # Create a list of names to fetch
  96.         names = ["distinguishedName"]
  97.         attrs = dir_ob.GetObjectAttributes(names)
  98.         for attr in attrs:
  99.             for val, typ in attr.Values:
  100.                 print "%s Attribute '%s' = %s" % (prefix, attr.AttrName, val)
  101.  
  102.     for child in ob:
  103.         _DumpObject(child, level+1)
  104.     
  105. def DumpAllObjects():
  106.     "Recursively dump the entire directory!"
  107.     path = "LDAP://%srootDSE" % server
  108.     rootdse = ADsGetObject(path)
  109.     name = rootdse.Get("defaultNamingContext")
  110.     
  111.     # Bind to the actual schema container.
  112.     path= "LDAP://" + server + name
  113.     print "Binding to", path
  114.     ob = ADsGetObject(path)
  115.  
  116.     # Enumerate the attribute and class objects in the schema container.
  117.     _DumpObject(ob)
  118.     
  119. ##########################################################
  120. #
  121. # Code taken from article:
  122. # Example Code for Enumerating Schema Classes, Attributes, and Syntaxes
  123.  
  124. # Fill a map with VT_ datatypes, to give us better names:
  125. vt_map = {}
  126. for name, val in pythoncom.__dict__.items():
  127.     if name[:3] == "VT_":
  128.         vt_map[val] = name
  129.  
  130. def DumpSchema2():
  131.     "Dumps the schema using an alternative technique"
  132.     path = "LDAP://%sschema" % (server,)
  133.     schema = ADsGetObject(path, IID_IADsContainer)
  134.     nclass = nprop = nsyntax = 0
  135.     for item in schema:
  136.         item_class = string.lower(item.Class)
  137.         if item_class == "class":
  138.             items = []
  139.             if item.Abstract: items.append("Abstract")
  140.             if item.Auxiliary: items.append("Auxiliary")
  141. #            if item.Structural: items.append("Structural")
  142.             desc = string.join(items, ", ")
  143.             import win32com.util
  144.             iid_name = win32com.util.IIDToInterfaceName(item.PrimaryInterface)
  145.             if verbose_level >= 2:
  146.                 print "Class: Name=%s, Flags=%s, Primary Interface=%s" % (item.Name, desc, iid_name)
  147.             nclass = nclass + 1
  148.         elif item_class == "property":
  149.             if item.MultiValued:
  150.                 val_type = "Multi-Valued"
  151.             else:
  152.                 val_type = "Single-Valued"
  153.             if verbose_level >= 2:
  154.                 print "Property: Name=%s, %s" % (item.Name, val_type)
  155.             nprop = nprop + 1
  156.         elif item_class == "syntax":
  157.             data_type = vt_map.get(item.OleAutoDataType, "<unknown type>")
  158.             if verbose_level >= 2:
  159.                 print "Syntax: Name=%s, Datatype = %s" % (item.Name, data_type)
  160.             nsyntax = nsyntax + 1
  161.     if verbose_level >= 1:
  162.         print "Processed", nclass, "classes"
  163.         print "Processed", nprop, "properties"
  164.         print "Processed", nsyntax, "syntax items"
  165.  
  166. def DumpGC():
  167.     "Dumps the GC: object (whatever that is!)"
  168.     ob = ADsGetObject("GC:", IID_IADsContainer)
  169.     for sub_ob in ob:
  170.         print "GC ob: %s (%s)" % (sub_ob.Name, sub_ob.ADsPath)
  171.  
  172. def DumpLocalUsers():
  173.     "Dumps the local machine users"
  174.     path = "WinNT://%s,computer" % (local_name,)
  175.     ob = ADsGetObject(path, IID_IADsContainer)
  176.     ob.put_Filter(["User", "Group"])
  177.     for sub_ob in ob:
  178.         print "User/Group: %s (%s)" % (sub_ob.Name, sub_ob.ADsPath)
  179.  
  180. def DumpLocalGroups():
  181.     "Dumps the local machine groups"
  182.     path = "WinNT://%s,computer" % (local_name,)
  183.     ob = ADsGetObject(path, IID_IADsContainer)
  184.  
  185.     ob.put_Filter(["Group"])
  186.     for sub_ob in ob:
  187.         print "Group: %s (%s)" % (sub_ob.Name, sub_ob.ADsPath)
  188.         # get the members
  189.         members = sub_ob.Members()
  190.         for member in members:
  191.             print "  Group member: %s (%s)" % (member.Name, member.ADsPath)
  192.  
  193. def usage(tests):
  194.     import os
  195.     print "Usage: %s [-s server ] [-v] [Test ...]" % os.path.basename(sys.argv[0])
  196.     print "  -v : Verbose - print more information"
  197.     print "  -s : server - execute the tests against the named server"
  198.     print "where Test is one of:"
  199.     for t in tests:
  200.         print t.__name__,":", t.__doc__
  201.     print
  202.     print "If not tests are specified, all tests are run"
  203.     sys.exit(1)
  204.  
  205. def main():
  206.     import getopt, traceback
  207.     tests = []
  208.     for ob in globals().values():
  209.         if type(ob)==type(main) and ob.__doc__:
  210.             tests.append(ob)
  211.     opts, args = getopt.getopt(sys.argv[1:], "s:hv")
  212.     for opt, val in opts:
  213.         if opt=="-s":
  214.             if val[-1] not in "\\/":
  215.                 val = val + "/"
  216.             global server
  217.             server = val
  218.         if opt=="-h":
  219.             usage(tests)
  220.         if opt=="-v":
  221.             global verbose_level
  222.             verbose_level = verbose_level + 1
  223.  
  224.     if len(args)==0:
  225.         print "Running all tests - use '-h' to see command-line options..."
  226.         dotests = tests
  227.     else:
  228.         dotests = []
  229.         for arg in args:
  230.             for t in tests:
  231.                 if t.__name__==arg:
  232.                     dotests.append(t)
  233.                     break
  234.             else:
  235.                 print "Test '%s' unknown - skipping" % arg
  236.     if not len(dotests):
  237.         print "Nothing to do!"
  238.         usage(tests)
  239.     for test in dotests:
  240.         try:
  241.             test()
  242.         except:
  243.             print "Test %s failed" % test.__name__
  244.             traceback.print_exc()
  245.  
  246. if __name__=='__main__':
  247.     main()