R01k
R01k

Reputation: 795

Python - Opening service with win32service returns Access Denied even as Administrator

If I try to control or even open some services with all access through win32service.OpenService() (running as administrator) I get "pywintypes.error: (5, 'OpenService', 'Access is denied.')". However, controlling the same services from the Services console is successful. Why is that? Here is sample code to replicate the problem:

import win32service as ws


def get_handle(service_name):
    # service_name is the internal service name, not the display name.
    hSCManager = ws.OpenSCManager(None, None, ws.SC_MANAGER_ALL_ACCESS)
    return ws.OpenService(hSCManager, service_name, ws.SERVICE_ALL_ACCESS)


sh = get_handle("CertPropSvc")  # Certificate Propagation, same problem with
                                # BitLocker Drive Encryption Service (BDESVC)

Upvotes: 1

Views: 1982

Answers (1)

R01k
R01k

Reputation: 795

Solved the problem by requesting lower permissions when opening SCM and the service:

import win32service as ws


def get_handle(service_name):
    # service_name is the internal service name, not the display name.
    # SC_MANAGER_CONNECT is enough.
    hSCManager = ws.OpenSCManager(None, None, ws.SC_MANAGER_CONNECT)
    # SERVICE_CHANGE_CONFIG is enough.
    return ws.OpenService(hSCManager, service_name, ws.SERVICE_CHANGE_CONFIG)


sh = get_handle("CertPropSvc")  # Certificate Propagation, BitLocker Drive
                                # Encryption Service (BDESVC) can also be used.

Upvotes: 1

Related Questions