Search code examples
pythonwindowsservicepsutil

psutil.WindowsService.username() returns blank


In my Win10 machine there a few services whose display name ends in "_5e11c". Windows Services console says that all of them log on as Local System. However, for any of them psutil.WindowsService.username() gives an empty string and if I query the process with psutil.Process.username() I get the user I'm logged in as:

>>> import psutil
>>>
>>> s = psutil.win_service_get("OneSyncSvc_5e11c")
>>> s
<WindowsService(name='OneSyncSvc_5e11c', display_name='Sync Host_5e11c') at 2203559523440>
>>> p = psutil.Process(s.pid())
>>> p
<psutil.Process(pid=8348, name='svchost.exe') at 2203559523160>
>>> p.username()
'FOO_PC\\BAR_USER'
>>> s.username()
''
>>>

What's going on?


Solution

  • The way psutil.WindowsService and psutil.Process work is slightly different, but one useful function they both share is as_dict()

    Using this, the information I got was more verbose:

    {'username': '', 'start_type': 'automatic', 'display_name': 'Sync 
    Host_11e740b', 'name': 'OneSyncSvc_11e740b', 'binpath': 'C:\\WINDOWS\\sy
    stem32\\svchost.exe -k UnistackSvcGroup', 'pid': 6492, 'status': 'running', 
    'description': 'This service synchronizes mail, contacts, calendar and
    various other user data. Mail and other applications dependent on 
    this functionality will not work properly when this service is
    not running.'}
    

    I saw that svchost had it running from the UnistackSvcGroup, so I opened task manager to find it and saw these other services listed under the same group

    list of other services that run under the same group

    If you check the username for anything running under the UnistackSvcGroup, all of them return without a username.

    Using the shared PID listed to check everything running under/attached to svchost, all services do not return a username. There's nothing wrong with your code.

    The single process is tied to many services and is running under your account, but the services themselves are running from your system. That is why the services return no username while svchost, which attaches these services to your account, itself does.

    This is explained in the comments by @eryksun as well:

    ""OneSyncSvc_*" is a new service type in Windows 10 -- a per-user service instance running in a shared process (i.e. SERVICE_USER_SERVICE | SERVICE_WIN32_SHARE_PROCESS | SERVICE_USERSERVICE_INSTANCE) as the user in the user's Session instead of running isolated in Session 0 as SYSTEM or a service account. It appears all service instances in the svchost process are suffixed with the same LUID (locally unique ID)

    There's also a "OneSyncSvc" user-service template (i.e. SERVICE_USER_SERVICE | SERVICE_WIN32_SHARE_PROCESS) defined in "HKLM\System\CurrentControlSet\Services". You can query its config on the command line via sc qc OneSyncSvc "