Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

win32netdemo.py 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import getopt
  2. import sys
  3. import traceback
  4. import win32api
  5. import win32net
  6. import win32netcon
  7. import win32security
  8. verbose_level = 0
  9. server = None # Run on local machine.
  10. def verbose(msg):
  11. if verbose_level:
  12. print(msg)
  13. def CreateUser():
  14. "Creates a new test user, then deletes the user"
  15. testName = "PyNetTestUser"
  16. try:
  17. win32net.NetUserDel(server, testName)
  18. print("Warning - deleted user before creating it!")
  19. except win32net.error:
  20. pass
  21. d = {}
  22. d["name"] = testName
  23. d["password"] = "deleteme"
  24. d["priv"] = win32netcon.USER_PRIV_USER
  25. d["comment"] = "Delete me - created by Python test code"
  26. d["flags"] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
  27. win32net.NetUserAdd(server, 1, d)
  28. try:
  29. try:
  30. win32net.NetUserChangePassword(server, testName, "wrong", "new")
  31. print("ERROR: NetUserChangePassword worked with a wrong password!")
  32. except win32net.error:
  33. pass
  34. win32net.NetUserChangePassword(server, testName, "deleteme", "new")
  35. finally:
  36. win32net.NetUserDel(server, testName)
  37. print("Created a user, changed their password, and deleted them!")
  38. def UserEnum():
  39. "Enumerates all the local users"
  40. resume = 0
  41. nuser = 0
  42. while 1:
  43. data, total, resume = win32net.NetUserEnum(
  44. server, 3, win32netcon.FILTER_NORMAL_ACCOUNT, resume
  45. )
  46. verbose(
  47. "Call to NetUserEnum obtained %d entries of %d total" % (len(data), total)
  48. )
  49. for user in data:
  50. verbose("Found user %s" % user["name"])
  51. nuser = nuser + 1
  52. if not resume:
  53. break
  54. assert nuser, "Could not find any users!"
  55. print("Enumerated all the local users")
  56. def GroupEnum():
  57. "Enumerates all the domain groups"
  58. nmembers = 0
  59. resume = 0
  60. while 1:
  61. data, total, resume = win32net.NetGroupEnum(server, 1, resume)
  62. # print "Call to NetGroupEnum obtained %d entries of %d total" % (len(data), total)
  63. for group in data:
  64. verbose("Found group %(name)s:%(comment)s " % group)
  65. memberresume = 0
  66. while 1:
  67. memberdata, total, memberresume = win32net.NetGroupGetUsers(
  68. server, group["name"], 0, resume
  69. )
  70. for member in memberdata:
  71. verbose(" Member %(name)s" % member)
  72. nmembers = nmembers + 1
  73. if memberresume == 0:
  74. break
  75. if not resume:
  76. break
  77. assert nmembers, "Couldnt find a single member in a single group!"
  78. print("Enumerated all the groups")
  79. def LocalGroupEnum():
  80. "Enumerates all the local groups"
  81. resume = 0
  82. nmembers = 0
  83. while 1:
  84. data, total, resume = win32net.NetLocalGroupEnum(server, 1, resume)
  85. for group in data:
  86. verbose("Found group %(name)s:%(comment)s " % group)
  87. memberresume = 0
  88. while 1:
  89. memberdata, total, memberresume = win32net.NetLocalGroupGetMembers(
  90. server, group["name"], 2, resume
  91. )
  92. for member in memberdata:
  93. # Just for the sake of it, we convert the SID to a username
  94. username, domain, type = win32security.LookupAccountSid(
  95. server, member["sid"]
  96. )
  97. nmembers = nmembers + 1
  98. verbose(" Member %s (%s)" % (username, member["domainandname"]))
  99. if memberresume == 0:
  100. break
  101. if not resume:
  102. break
  103. assert nmembers, "Couldnt find a single member in a single group!"
  104. print("Enumerated all the local groups")
  105. def ServerEnum():
  106. "Enumerates all servers on the network"
  107. resume = 0
  108. while 1:
  109. data, total, resume = win32net.NetServerEnum(
  110. server, 100, win32netcon.SV_TYPE_ALL, None, resume
  111. )
  112. for s in data:
  113. verbose("Found server %s" % s["name"])
  114. # Now loop over the shares.
  115. shareresume = 0
  116. while 1:
  117. sharedata, total, shareresume = win32net.NetShareEnum(
  118. server, 2, shareresume
  119. )
  120. for share in sharedata:
  121. verbose(
  122. " %(netname)s (%(path)s):%(remark)s - in use by %(current_uses)d users"
  123. % share
  124. )
  125. if not shareresume:
  126. break
  127. if not resume:
  128. break
  129. print("Enumerated all the servers on the network")
  130. def LocalGroup(uname=None):
  131. "Creates a local group, adds some members, deletes them, then removes the group"
  132. level = 3
  133. if uname is None:
  134. uname = win32api.GetUserName()
  135. if uname.find("\\") < 0:
  136. uname = win32api.GetDomainName() + "\\" + uname
  137. group = "python_test_group"
  138. # delete the group if it already exists
  139. try:
  140. win32net.NetLocalGroupDel(server, group)
  141. print("WARNING: existing local group '%s' has been deleted.")
  142. except win32net.error:
  143. pass
  144. group_data = {"name": group}
  145. win32net.NetLocalGroupAdd(server, 1, group_data)
  146. try:
  147. u = {"domainandname": uname}
  148. win32net.NetLocalGroupAddMembers(server, group, level, [u])
  149. mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level)
  150. print("members are", mem)
  151. if mem[0]["domainandname"] != uname:
  152. print("ERROR: LocalGroup just added %s, but members are %r" % (uname, mem))
  153. # Convert the list of dicts to a list of strings.
  154. win32net.NetLocalGroupDelMembers(
  155. server, group, [m["domainandname"] for m in mem]
  156. )
  157. finally:
  158. win32net.NetLocalGroupDel(server, group)
  159. print("Created a local group, added and removed members, then deleted the group")
  160. def GetInfo(userName=None):
  161. "Dumps level 3 information about the current user"
  162. if userName is None:
  163. userName = win32api.GetUserName()
  164. print("Dumping level 3 information about user")
  165. info = win32net.NetUserGetInfo(server, userName, 3)
  166. for key, val in list(info.items()):
  167. verbose("%s=%s" % (key, val))
  168. def SetInfo(userName=None):
  169. "Attempts to change the current users comment, then set it back"
  170. if userName is None:
  171. userName = win32api.GetUserName()
  172. oldData = win32net.NetUserGetInfo(server, userName, 3)
  173. try:
  174. d = oldData.copy()
  175. d["usr_comment"] = "Test comment"
  176. win32net.NetUserSetInfo(server, userName, 3, d)
  177. new = win32net.NetUserGetInfo(server, userName, 3)["usr_comment"]
  178. if str(new) != "Test comment":
  179. raise RuntimeError("Could not read the same comment back - got %s" % new)
  180. print("Changed the data for the user")
  181. finally:
  182. win32net.NetUserSetInfo(server, userName, 3, oldData)
  183. def SetComputerInfo():
  184. "Doesnt actually change anything, just make sure we could ;-)"
  185. info = win32net.NetWkstaGetInfo(None, 502)
  186. # *sob* - but we can't! Why not!!!
  187. # win32net.NetWkstaSetInfo(None, 502, info)
  188. def usage(tests):
  189. import os
  190. print("Usage: %s [-s server ] [-v] [Test ...]" % os.path.basename(sys.argv[0]))
  191. print(" -v : Verbose - print more information")
  192. print(" -s : server - execute the tests against the named server")
  193. print(" -c : include the CreateUser test by default")
  194. print("where Test is one of:")
  195. for t in tests:
  196. print(t.__name__, ":", t.__doc__)
  197. print()
  198. print("If not tests are specified, all tests are run")
  199. sys.exit(1)
  200. def main():
  201. tests = []
  202. for ob in list(globals().values()):
  203. if type(ob) == type(main) and ob.__doc__:
  204. tests.append(ob)
  205. opts, args = getopt.getopt(sys.argv[1:], "s:hvc")
  206. create_user = False
  207. for opt, val in opts:
  208. if opt == "-s":
  209. global server
  210. server = val
  211. if opt == "-h":
  212. usage(tests)
  213. if opt == "-v":
  214. global verbose_level
  215. verbose_level = verbose_level + 1
  216. if opt == "-c":
  217. create_user = True
  218. if len(args) == 0:
  219. print("Running all tests - use '-h' to see command-line options...")
  220. dotests = tests
  221. if not create_user:
  222. dotests.remove(CreateUser)
  223. else:
  224. dotests = []
  225. for arg in args:
  226. for t in tests:
  227. if t.__name__ == arg:
  228. dotests.append(t)
  229. break
  230. else:
  231. print("Test '%s' unknown - skipping" % arg)
  232. if not len(dotests):
  233. print("Nothing to do!")
  234. usage(tests)
  235. for test in dotests:
  236. try:
  237. test()
  238. except:
  239. print("Test %s failed" % test.__name__)
  240. traceback.print_exc()
  241. if __name__ == "__main__":
  242. main()