8

The Python pwd module provides access to getpwnam(3) POSIX API, which can be used to get the home directory for a particular user by username, as well determining if the username is valid at all. pwd.getpwnam will raise an exception if called with a non-existent username.

At first it seems like the same result can be achieved in a cross-platform manner via os.path.expanduser('~username'). However, it appears that with Python 2.6 on Windows XP this won't actually produce a failure for a non-existent username. Furthermore, on Python 2.5 on Windows XP, it seems to fail even for valid users.

Can this information be obtained reliably on Windows? How?

2
  • 1
    Always love a good "Python on Windows" question. The sooner we bring enlightenment to that platform (if it's possible), the better for all. Jul 22, 2010 at 4:32
  • ~user is not supposed to work on 2.5, it is implemented in 2.6+ but in a broken way - see my answer below for working implementation. Yes, had to peek in registry i am afraid.
    – Nas Banov
    Jul 28, 2010 at 21:53

4 Answers 4

4

Reading the 2.6 documentation shows that os.path.expanduser() is broken on Windows:

On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.

Say whaat? This assumes all user homes have to be under the same parent directory. Nuh-ugh!

It was a bit hard to dig but here is a solution that will look up a local user by given name:

from win32security import LookupAccountName, ConvertSidToStringSid
from _winreg import OpenKey, QueryValueEx, HKEY_LOCAL_MACHINE

def getUserDir(userName):
    ssid = ConvertSidToStringSid(LookupAccountName(None, userName)[0])
    key = OpenKey(HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\\' + ssid)
    return QueryValueEx(key, 'ProfileImagePath')[0]
5
  • 1
    this yields results only for local users?
    – akira
    Jul 22, 2010 at 8:18
  • 1
    This getUserDir looks promising. I tried it out on my problem but unfortunately immediately ran into a problem where my code is running as a service which apparently isn't mapped to a user (somehow), so one of the calls failed (with an exception complaining about the lack of such a mapping). For the time being I stopped there, but I'll probably revisit this at some point. Perhaps once I set up whatever mapping is required, this function will satisfy the requirements. Jul 28, 2010 at 22:43
  • 1
    @Jean-Paul: ah, this seems entirely another issue. By default win services run under "built-in security principal" LocalService, which is sort of a user but may have some limitations (no NetBEUI, no GUI). Optionally you can choose to run a service under another, particular user login. E.g. PostgreSQL runs its daemon under user "postgres".
    – Nas Banov
    Jul 28, 2010 at 23:24
  • The nearest equivalent of pwd.getpwnam would be win32net.NetUserGetInfo with level 4 inormation. The result includes the user's home_dir and roaming profile directory. In case they're both empty, it also includes the user_sid to look up the local profile directory.
    – Eryk Sun
    Aug 5, 2020 at 18:34
  • The problem is that the system has separate concepts of 'profile' and 'home', which, for the current user, are accessed as %USERPROFILE% and %HOMEDRIVE%%HOMEPATH%. The bigger problem is that known user folders (e.g. "Desktop") can be individually set to any local or remote directory instead of the defaults in the profile directory. Determining this requires loading the user's profile registry hive ("ntuser.dat") with winreg.LoadKey (backup/restore privilege) and reading values from the user's "Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders".
    – Eryk Sun
    Aug 5, 2020 at 18:45
3

I am new to Windows security... but reading MSDN and some blogs it seems to me that the way MS want us to handle other users specific data is by getting a user token.

There used to be a nice wiki of Keith Brown .Net Developers Guide to Windows Security... you can still find it in Google cache for "pluralsight keith.guidebook"

Case 1: If you don't have the user password:

For local accounts you can try reading the Windows registry as Nas Banov already suggested and there are some other recipes on SO or the Internet.

I am not sure how various Windows versions behaves for freshly create users ... those which have never performed an interactive session login ... does it automatically creates their registry, home folder and profile data? I have done some tests on Windows XP and those registry keys were not present after creating an local account ... but in this case you can try to guess it based in All Users registry values ... or just fail :)

For desktop applications, when the application is running as a logged in user, I am using something like this to get the home folder.... and to get the equivalent of ~/.local I am using CSIDL_APPDATA, for roaming profiles, or just CSIDL_LOCAL_APPDATA.

from win32com.shell import shell, shellcon
# See microsoft references for further CSIDL constants
# http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx
folder_name = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, 0, 0)

Reading Keith Brown article "How To Get A Token For A User" .. you can look for some other ways of getting an user token without a password...

Case 2: If you have the user password:

Reading the MSDN I got the impressing that if I have an user token, I can get its folders by calling something like the code below... but it did not worked for me. (not sure why)

token = win32security.LogonUser(
            username,
            None, # we uses UPN format for username
            password,
            win32security.LOGON32_LOGON_NETWORK,
            win32security.LOGON32_PROVIDER_DEFAULT,
            )
folder_name = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, token, 0)

This is why I ended up with this code...which is far from being perfect due to the fact that it requires username and password.

token = win32security.LogonUser(
            username,
            None, # Here should be the domain ... or just go with default values
            password,
            win32security.LOGON32_LOGON_NETWORK,
            win32security.LOGON32_PROVIDER_DEFAULT,
            )
win32security.ImpersonateLoggedOnUser(token)
folder_name = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, 0, 0)
win32security.RevertToSelf()

This question is somehow related: How to find the real user home directory using python?

0

you could go the win32api.GetUserName() (current user only) or win32net.NetUserGetInfo() (any user on any server, localhost included) route. the latter could be a bit slow since it can take some time to get this information back from the OS.

  import win32net

  def userDir(username):
        return win32net.NetUserGetInfo(None, username, 1).get("home_dir")

alternatively you could expand the environment variable USERPROFILE on windows or HOME on unix to get the information about the currently logged in user:

  def userDir():
      if os.platform.system() == 'Windows':
          return os.environ['USERPROFILE']
      elif os.platform.system() == 'Linux':
          return os.environ['HOME'] 
      else:
          return None
7
  • Won't work - this will return info only for the current user. The question is about any, 'particular' user.
    – Nas Banov
    Jul 22, 2010 at 5:37
  • @Nas Banov: true, but only for the 2nd part of my answer. win32api.NetUserGetInfo () retrieves the information for ANY user.
    – akira
    Jul 22, 2010 at 7:42
  • @Akira: Sounds nice but how? win32net.NetUserGetInfo(None, userName, 4)) returns 'home_dir': u'', i.e. useless
    – Nas Banov
    Jul 22, 2010 at 7:53
  • @Nas Banov: yes. interesting, isn't it? could be a Windows7 issue?
    – akira
    Jul 22, 2010 at 8:06
  • @Akira: I doubt issue is win7 related, since i tested on XP. Probably need to RTFM for gory details
    – Nas Banov
    Jul 22, 2010 at 8:12
0

This seems to be only applicable to the current user, but on my (winxp) machine, os.path.expanduser('~') returns my home directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.