Windows下与pwd.getpwnam(username).pw_dir等效的东西是什么? [英] What is the Windows equivalent of pwd.getpwnam(username).pw_dir?

查看:246
本文介绍了Windows下与pwd.getpwnam(username).pw_dir等效的东西是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python pwd模块提供对getpwnam(3) POSIX API的访问,该API可用于通过用户名获取特定用户的主目录,以及确定用户名是否有效.如果使用不存在的用户名调用pwd.getpwnam,则会引发异常.

首先,似乎可以通过os.path.expanduser('~username')以跨平台的方式实现相同的结果.但是,似乎在Windows XP上使用Python 2.6时,对于不存在的用户名实际上不会产生故障.此外,在Windows XP上的Python 2.5上,即使对于有效用户,它似乎也会失败.

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

解决方案

阅读 解决方案

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]

这篇关于Windows下与pwd.getpwnam(username).pw_dir等效的东西是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆