mhammond / pywin32

Python for Windows (pywin32) Extensions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

pywintypes.error: (5, 'RegOpenKeyEx', 'Access is denied.') when running service with debug parameter and no elevation

jmartens opened this issue · comments

For all bugs, please provide the following information:

Expected behavior and actual behavior

When trying to debug a windows service following this StackOverflow post I get the following access when running my service in debug mode (from IDE and console):

C:\Users\jonathan.martens\Code\poc-winservice-in-venv\venv\Scripts\python.exe -m winsvc debug 
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "C:\Users\jonathan.martens\Code\poc-winservice-in-venv\winsvc.py", line 103, in <module>
    win32serviceutil.HandleCommandLine(Win32ServiceWrapper)
  File "C:\Users\jonathan.martens\Code\poc-winservice-in-venv\venv\Lib\site-packages\win32\lib\win32serviceutil.py", line 796, in HandleCommandLine
    exeName = LocateSpecificServiceExe(serviceName)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\jonathan.martens\Code\poc-winservice-in-venv\venv\Lib\site-packages\win32\lib\win32serviceutil.py", line 119, in LocateSpecificServiceExe
    hkey = win32api.RegOpenKey(
           ^^^^^^^^^^^^^^^^^^^^
pywintypes.error: (5, 'RegOpenKeyEx', 'Access is denied.')

Process finished with exit code 1

This is most likely due to the access level that is requested due to win32con.KEY_ALL_ACCESS at

hkey = win32api.RegOpenKey(
win32con.HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName),
0,
win32con.KEY_ALL_ACCESS,
)

If I reduce the access level to win32con.KEY_QUERY_VALUE it works even if not elevated, without this change controlling or running the service in debug mode requires an elevated shell:

hkey =win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, rf"SYSTEM\CurrentControlSet\Services\{serviceName}", 1, win32con.KEY_QUERY_VALUE)
win32api.RegQueryValueEx(hkey, "ImagePath")[0]
'"c:\\Users\\jonathan.martens\\Code\\poc-winservice-in-venv\\venv\\Scripts\\pythonservice.exe"'

Steps to reproduce the problem

See above.

System information

Python version and distribution:

pywin32 version:
c:\Users\jonathan.martens\Code\poc-winservice-in-venv>venv\Scripts\python -V
Python 3.12.2

Installed from PyPI or exe installer:
pypi

Windows Version:
Microsoft Windows [Version 10.0.19045.4170]

DLL locations:

c:\Users\jonathan.martens\Code\poc-winservice-in-venv>venv\Scripts\python -c "import pywintypes,pythoncom;print(pywintypes.__file__,pythoncom.__file__,sep='\n')"
c:\Users\jonathan.martens\Code\poc-winservice-in-venv\venv\Lib\site-packages\pywin32_system32\pywintypes312.dll
c:\Users\jonathan.martens\Code\poc-winservice-in-venv\venv\Lib\site-packages\pywin32_system32\pythoncom312.dll