17

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.

4

5 回答 5

27

尝试这个:

import os;
print os.environ.get( "USERNAME" )

那应该做的工作。

于 2008-09-22T19:42:41.070 回答
5

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.

于 2014-07-09T09:25:26.687 回答
2
win32api.GetUserName()

win32api.GetUserNameEx(...) 

见: http ://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html

于 2010-01-02T21:31:16.900 回答
1

我不知道 Python,但对于 Windows,底层 api 是GetUserNameEx,如果 os.environ.get( "USERNAME" ) 没有告诉你你需要知道的一切,我假设你可以在 Python 中调用它。

于 2008-09-22T19:48:00.590 回答
-1

很老的问题,但要刷新原始问题的答案“如何使用 python 脚本检索当前登录用户的名称?” 利用:

import os
print (os.getlogin())

根据 Python 文档: getlogin - 返回在进程的控制终端上登录的用户的名称。

于 2014-05-30T21:29:28.983 回答