Python - checking if a user has administrator rights

I am writing a small program as a self-learning project in Python 3.x. My idea is that the program allows the user to enter two text input fields, and then insert user input into the value of two specific registry keys.

Is there an easy way to get him to check if the current user can access the registry? I would prefer that he clearly tell the user that he needs administrator rights than for the program to go crazy and crash, because he is trying to access the restricted area.

I would like this check to be performed immediately after starting the program, before any input parameters are provided to the user. What code is needed for this?

Edit: in case this is not obvious, this applies to Windows platforms.

+3
source share
4 answers

With pywin32 , something like the following should work ...:

import pythoncom
import pywintypes
import win32api
from win32com.shell import shell

if shell.IsUserAnAdmin():
   ...

And yes, it looks like pywin32 supports Python 3.

+6
source

I needed a simple Windows / Posix solution to check if the user has root / admin rights on the file system without installing a third-party solution. I understand that there are vulnerabilities when using environment variables, but they are consistent with my goal. Perhaps you can expand this approach for reading / writing the registry.

Python 2.6/2.7 WinXP, WinVista Wine. - , Pyton 3.x / Win7, , . .

def has_admin():
    import os
    if os.name == 'nt':
        try:
            # only windows users with admin privileges can read the C:\windows\temp
            temp = os.listdir(os.sep.join([os.environ.get('SystemRoot','C:\\windows'),'temp']))
        except:
            return (os.environ['USERNAME'],False)
        else:
            return (os.environ['USERNAME'],True)
    else:
        if 'SUDO_USER' in os.environ and os.geteuid() == 0:
            return (os.environ['SUDO_USER'],True)
        else:
            return (os.environ['USERNAME'],False)
+6

Here's a short article on how to determine if an application requires elevated privileges .

You can use pywin32 or ctypes to call CreateProcess ().

I suggest ctypes, as it is now part of the python standard, and there is a good example of using CreateProcess with ctypes here .

+4
source

The easiest way is to change the key at the beginning, possibly to the value of the stub - if this fails, catch the error and inform the user.

+1
source

Source: https://habr.com/ru/post/1747913/


All Articles