win32cred_demo.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """
  2. Demonstrates prompting for credentials, saving, and loggging on with marshalled credential.
  3. Also shows how to load user's profile
  4. """
  5. import win32net, win32security, win32api, win32con
  6. import win32profile, win32cred
  7. ## Prompt for a username/pwd for local computer
  8. uiinfo={'MessageText':'Enter credentials for local machine','CaptionText':'win32cred_demo.py'}
  9. target, pwd, save=win32cred.CredUIPromptForCredentials(TargetName=win32api.GetComputerName(), AuthError=0,
  10. Flags=win32cred.CREDUI_FLAGS_DO_NOT_PERSIST|win32cred.CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX,
  11. Save=False, UiInfo=uiinfo)
  12. attrs=[
  13. {'Keyword':'attr1', 'Flags':0, 'Value':'unicode data'},
  14. {'Keyword':'attr2', 'Flags':0, 'Value':'character data'}
  15. ]
  16. cred={'Comment':'Created by win32cred_demo.py', 'UserName':target, 'TargetAlias': None,
  17. 'TargetName':target,'CredentialBlob':pwd, 'Flags':win32cred.CRED_FLAGS_USERNAME_TARGET,
  18. 'Persist':win32cred.CRED_PERSIST_ENTERPRISE,'Type':win32cred.CRED_TYPE_DOMAIN_PASSWORD,
  19. 'Attributes':attrs}
  20. win32cred.CredWrite(cred)
  21. pwd=None
  22. print(win32cred.CredRead(target, win32cred.CRED_TYPE_DOMAIN_PASSWORD))
  23. ## Marshal saved credential and use it to log on
  24. mc=win32cred.CredMarshalCredential(win32cred.UsernameTargetCredential, target)
  25. th=win32security.LogonUser(mc,None,'',win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT)
  26. win32security.ImpersonateLoggedOnUser(th)
  27. print('GetUserName:',win32api.GetUserName())
  28. win32security.RevertToSelf()
  29. ## Load user's profile. (first check if user has a roaming profile)
  30. username, domain=win32cred.CredUIParseUserName(target)
  31. user_info_4=win32net.NetUserGetInfo(None, username, 4)
  32. profilepath=user_info_4['profile']
  33. ## LoadUserProfile apparently doesn't like an empty string
  34. if not profilepath:
  35. profilepath=None
  36. ## leave Flags in since 2.3 still chokes on some types of optional keyword args
  37. hk=win32profile.LoadUserProfile(th, {'UserName':username, 'Flags':0, 'ProfilePath':profilepath})
  38. ## Get user's environment variables in a form that can be passed to win32process.CreateProcessAsUser
  39. env=win32profile.CreateEnvironmentBlock(th,False)
  40. ## Cleanup should probably be in a finally block
  41. win32profile.UnloadUserProfile(th, hk)
  42. th.Close()