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.
-
you wanna check out http://stackoverflow.com/a/842096/611007 not sure about domain – n611x007 Jul 09 '14 at 09:23
5 Answers
Try this:
import os;
print os.environ.get( "USERNAME" )
That should do the job.
-
1@Marcel Levy - i know its pretty old, but for the rest who stumble on this... os.environ is returning a dictionary. get("USERNAME") is looking the key in the dict. – sbartell Jul 06 '11 at 23:46
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
I don't know Python, but for windows the underlying api is GetUserNameEx, I assume you can call that in Python if os.environ.get( "USERNAME" ) doesn't tell you everything you need to know.

- 1,524
- 4
- 20
- 31
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.

- 3,318
- 2
- 42
- 54

- 13
- 3
-
3Since we're all responding to old items anyways, the original question was how to get the **Windows** User login name - `os.getlogin()` is not available in Windows versions of Python. – Raceyman Jul 03 '14 at 13:46
-