localized_names.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # A Python port of the MS knowledge base article Q157234
  2. # "How to deal with localized and renamed user and group names"
  3. # http://support.microsoft.com/default.aspx?kbid=157234
  4. import sys
  5. from win32net import NetUserModalsGet
  6. from win32security import LookupAccountSid
  7. import pywintypes
  8. from ntsecuritycon import *
  9. def LookupAliasFromRid(TargetComputer, Rid):
  10. # Sid is the same regardless of machine, since the well-known
  11. # BUILTIN domain is referenced.
  12. sid = pywintypes.SID()
  13. sid.Initialize(SECURITY_NT_AUTHORITY, 2)
  14. for i, r in enumerate((SECURITY_BUILTIN_DOMAIN_RID, Rid)):
  15. sid.SetSubAuthority(i, r)
  16. name, domain, typ = LookupAccountSid(TargetComputer, sid)
  17. return name
  18. def LookupUserGroupFromRid(TargetComputer, Rid):
  19. # get the account domain Sid on the target machine
  20. # note: if you were looking up multiple sids based on the same
  21. # account domain, only need to call this once.
  22. umi2 = NetUserModalsGet(TargetComputer, 2)
  23. domain_sid = umi2['domain_id']
  24. SubAuthorityCount = domain_sid.GetSubAuthorityCount()
  25. # create and init new sid with acct domain Sid + acct Rid
  26. sid = pywintypes.SID()
  27. sid.Initialize(domain_sid.GetSidIdentifierAuthority(),
  28. SubAuthorityCount+1)
  29. # copy existing subauthorities from account domain Sid into
  30. # new Sid
  31. for i in range(SubAuthorityCount):
  32. sid.SetSubAuthority(i, domain_sid.GetSubAuthority(i))
  33. # append Rid to new Sid
  34. sid.SetSubAuthority(SubAuthorityCount, Rid)
  35. name, domain, typ = LookupAccountSid(TargetComputer, sid)
  36. return name
  37. def main():
  38. if len(sys.argv) == 2:
  39. targetComputer = sys.argv[1]
  40. else:
  41. targetComputer = None
  42. name = LookupUserGroupFromRid(targetComputer, DOMAIN_USER_RID_ADMIN)
  43. print("'Administrator' user name = %s" % (name,))
  44. name = LookupAliasFromRid(targetComputer, DOMAIN_ALIAS_RID_ADMINS)
  45. print("'Administrators' local group/alias name = %s" % (name,))
  46. if __name__=='__main__':
  47. main()