win32netdemo.py 8.4 KB

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