test.py 7.1 KB

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