加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

什么是Windows等价的pwd.getpwnam(用户名).pw_dir?

发布时间:2020-12-14 04:07:12 所属栏目:Windows 来源:网络整理
导读:Python pwd模块提供对getpwnam(3)POSIX API的访问,该API可用于通过用户名获取特定用户的主目录,以及确定用户名是否有效.如果使用不存在的用户名调用,pwd.getpwnam将引发异常. 起初,似乎可以通过os.path.expanduser(‘~username’)以跨平台方式实现相同的结果
Python pwd模块提供对getpwnam(3)POSIX API的访问,该API可用于通过用户名获取特定用户的主目录,以及确定用户名是否有效.如果使用不存在的用户名调用,pwd.getpwnam将引发异常.

起初,似乎可以通过os.path.expanduser(‘~username’)以跨平台方式实现相同的结果.但是,似乎在Windows XP上使用Python 2.6,这实际上不会导致不存在的用户名失败.此外,在Windows XP上的Python 2.5上,即使对于有效用户来说似乎也失败了.

可以在Windows上可靠地获取此信息吗?怎么样?

阅读 2.6 documentation表明os.path.expanduser()在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.

说什么?这假设所有用户家庭必须位于同一父目录下.新加坡国立大学医院,唉!

这有点难以挖掘,但这里有一个解决方案,它将通过给定名称查找本地用户:

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'SOFTWAREMicrosoftWindows NTCurrentVersionProfileList' + ssid)
    return QueryValueEx(key,'ProfileImagePath')[0]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读