Python: How to get domain\username for logged in user
15,204
Solution 1
Here you go :
import os
domain = os.environ['userdomain']
print(domain)
(But i see that this doest give the FQDN, but only the NetBIOS name)
Solution 2
If you have pywin32
installed, you can call the corresponding Windows function:
import win32api
win32api.GetUserNameEx(win32api.NameSamCompatible)
Check out this MSDN page for other possible parameters and outputs.
Solution 3
Should work in Python 2 and 3
import getpass
import platform
print(getpass.getuser()) #username
print(platform.node()) #hostname
Comments
-
Robben_Ford_Fan_boy about 2 years
In Python how do I get the logged in username in the domain\username format. The following just get username:
import getpass import os print(os.getlogin()) print(getpass.getuser())
-
Serge Ballesta over 7 yearsDomainname here represent the Active Directory (or Windows NT for dinosaurs...) domain. It can be different from the host name.
-
leancz over 7 yearsgetpass.getuser() + '\\' + os.environ['userdnsdomain']
-
Robben_Ford_Fan_boy over 7 yearsThat returns the domain name of the Computer
-
Amperclock over 7 years@leancz yhea, that gives you averything at once
-
Eryk Sun over 7 yearsThis returns the logon session user name, which should also be available as the
%USERNAME%
and%USERDOMAIN%
environment variables. This name almost always agrees with the user SID in the process access token, except the 3 common service accounts (i.e. SYSTEM, LOCAL SERVICE, and NETWORK SERVICE) get logged on as the machine name followed by a dollar sign (e.g. "SPAMBOX$"). That may surprise you if you're running as a service using one of those accounts.