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:
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.
Using a Python LDAP library, e.g. ldap3
This follows the standard LDAP protocol, with a pure Python implementation, so should work from any client OS.
Using raw LDAP queries is rather more involved than the ADSI abstractions. I suggest you read the documentation (which has decent tutorials) and search for more tutorials on interacting with Microsoft AD via ldap3.
Note that one possible issue is that searching by username (CN) alone might get you the wrong object. It's possible to have multiple objects with the same CN across multiple OUs. If you want to be more precise, you might want to use a unique identifier like the SID.
4Based on the comments from @Bob, the following is working on Windows and is pure Python but it requires to install pywin32 (based on this Recipe):
import win32api
import win32net
user_info = win32net.NetUserGetInfo(win32net.NetGetAnyDCName(), win32api.GetUserName(), 2)
full_name = user_info["full_name"]Another shorter version of the script in the question using only subprocess is:
import subprocess
name = subprocess.check_output( 'net user "%USERNAME%" /domain | FIND /I "Full Name"', shell=True
)
full_name name.replace(b"Full Name", b"").strip()NOTE: in the last example, you will need to change the last line to ...replace("Full Name", "").strip() for Python 2.7.