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.

GEOCHET
  • 20,623
  • 15
  • 71
  • 98

5 Answers5

27

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

Community
  • 1
  • 1
n611x007
  • 7,979
  • 7
  • 53
  • 91
2
win32api.GetUserName()

win32api.GetUserNameEx(...) 

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

sra
  • 23,629
  • 7
  • 52
  • 88
Adam
  • 320
  • 2
  • 3
1

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.

Jim In Texas
  • 1,514
  • 3
  • 20
  • 29
-1

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.

JabberwockyDecompiler
  • 3,068
  • 2
  • 34
  • 51
gaur_ab
  • 13
  • 3
  • 3
    Since 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
  • Question mentioned Windows. – Kostadin Nov 07 '17 at 09:10