Search code examples
pythonpython-3.xwinapiwindows-servicesgetpass

getpass.getuser / os.environ['username'] returns computer name and not username


I made a service with python which will call this app made with pyinstaller using subprocess.popen. It makes a call to getpass.getuser() but instead of the username it returns the computer-name.

I've tried getpass.getuser() / os.environ['username'] / win32api.GetUserName() but all return Computer-Name and not username.

BTW here, computer name refers to "DESKTOP-Q..." and username is the username of the person logged in ( here "wasim" )

Any method to get the username and not the computer-name ?


Solution

  • Ok i solved it ! not by using getpass but by using psutil. so the service by default runs under LOCAL SYSTEM account, which means it's running in a completely different environment. my situation required me to have the service running in LOCAL SYSTEM account and not the user's account as the user of the system may change ( from AD ). to achieve this i did...

    >>> import psutil
    >>> psutil.users()[0].name
    

    psutil.users() returns a list of logged in users