Full Name of Windows User Name (In Domain) Using Python
I Want to Retrieve the Full Name of a Windows Computer User in Python. I Have Found the Equivalent Batch Command: Net User "%Username%" /Domain | Find /I "Full...
I want to retrieve the full name of a Windows computer user in Python.
I have found the equivalent batch command:
net user "%USERNAME%" /domain | FIND /I "Full Name"
that returns the full name (e.g. Full Name John Doe).
I have done the following way by using subprocess but I am wondering if there is a more native way to do it with some Python modules.
import getpass
import subprocess
import re
username = getpass.getuser()
p = subprocess.Popen(
'net user %s /domain' % username,
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
info, err = p.stdout.read(), p.stderr.read()
full_name = re.findall(r'Full Name\s+(.*\S)', info)
print(full_name)
Thanks
2 Answers
The more direct way to do this is to query Active Directory. You'd perform a lookup on the user, followed by getting the displayName attribute. (This maps to the Full Name displayed in Windows.)
You have two options here:
Must Read
Using a Python AD library, e.g. pyad
This is very Windows-specific, and requires the pywin32 library. It relies on ADSI APIs, so it will only works on Windows.
from pyad import aduser
user = aduser.ADUser.from_cn(username)
print(user.get_attribute("displayName"))
How you get the username is up to you. You can use getpass.getuser(), os.environ["USERNAME"] (Windows-only), etc.