How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.
5 回答
尝试这个:
import os;
print os.environ.get( "USERNAME" )
那应该做的工作。
as in https://stackoverflow.com/a/842096/611007 by Konstantin Tenzin
Look at getpass module
import getpass getpass.getuser()
Availability: Unix, Windows
Note "this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other)."
at least, definitely preferable over getenv
.
win32api.GetUserName()
win32api.GetUserNameEx(...)
见: http ://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html
我不知道 Python,但对于 Windows,底层 api 是GetUserNameEx,如果 os.environ.get( "USERNAME" ) 没有告诉你你需要知道的一切,我假设你可以在 Python 中调用它。
很老的问题,但要刷新原始问题的答案“如何使用 python 脚本检索当前登录用户的名称?” 利用:
import os
print (os.getlogin())
根据 Python 文档: getlogin - 返回在进程的控制终端上登录的用户的名称。