Reputation: 77
I'm running the same Python script for different users on my PC (Windows 10). This script has to get the user who is actually logged in. For example getpass.getuser()
isn't working because it just returns the user for which the Python script is running. How can I get this? Thanks for help!
Upvotes: 1
Views: 5102
Reputation: 25789
The whole point of Run as... is to mimic the environment of another user so, naturally, when you query for the username (which essentially gets you the value of %USERNAME%
env. variable) you'll get the one under which you're running the script.
To get the currently logged in user, you'll have prod the current session, and to do that, at the very least, you'll have to query WMIC (or access the Win32 API directly). Something like:
import subprocess
def get_session_user():
res = subprocess.check_output(["WMIC", "ComputerSystem", "GET", "UserName"],
universal_newlines=True)
_, username = res.strip().rsplit("\n", 1)
return username.rsplit("\\", 1)
Beware that this will return a tuple containing both the system/domain of the currently logged-in user and the username itself, so call it as:
system, username = get_session_user()
To get both.
Upvotes: 2