简体   繁体   中英

How to Retrieve name of current Windows User (AD or local) using Python?

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.

Try this:

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

That should do the job.

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(...) 

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

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

Pretty old question but to refresh the answer to the original question "How can I retrieve the name of the currently logged in user, using a python script?" use:

import os
print (os.getlogin())

Per Python documentation: getlogin - Return the name of the user logged in on the controlling terminal of the process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM