I'm having a little trouble getting the current logged on user from a pyhton windows service.
I've tried using os.getEnv("username") - same as os.environs["username"] - which failed - they return None.
So I tried using win32api: userName = win32api.GetUserName()
which returned SYSTEM
Which I assume is returning the 'user' who's running the service.
So I tried dipping into the registry using: # hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer') # userName, type = win32api.RegQueryValueEx(hkey, 'Logon User Name')
However, this again failed returning None or SYSTEM, I can't remeber which.
So I think what's happening is that the pythonservice.exe is running as a SYSTEM process, so when it does a call to get the current logged on user (using any of the methods I've tried) they all ultimately point back to the HKEY_USERS reg entry for SYSTEM & not the user who's logged onto the PC.
Does anyone have any idea to get the actual logged on user of the PC via a windows service?
I'm at a loss other than using a logon script to create an entry / file with the %USERNAME% stored somewhere!?!?
Try the getpass module, it looks for these keys in the os.environ for a suitable username: ('LOGNAME', 'USER', 'LNAME', 'USERNAME') This should work in windows, cant test it, sorry too busy running linux.
Once again it worked fine when the app is run by the user. But when I ran the app as a windows service it didn't return a user name, but raised an exception (as per the documentaion for the getuser() method).
I have managed to get the functionality I want via the use of logon & logoff scripts. When a user logs on his name is added to a text file, when he logs off his name is removed from the file.
My python windows service app reads this text file to see who's logged on!
Not ideal, but as windows doesn't seem able to provide the info straight out of the box.....
Can't believe windows doesn't have a working equivalent to 'who', 'last', etc as in linux!