8

I'm writing a little program as a self-learning project in Python 3.x. My idea is for the program to allow two fields of text entry to the user, and then plug the user's input into the value of two specific registry keys.

Is there a simple way to make it check if the current user can access the registry? I'd rather it cleanly tell the user that he/she needs administrator privileges than for the program to go nuts and crash because it's trying to access a restricted area.

I'd like it to make this check as soon as the program launches, before the user is given any input options. What code is needed for this?

Edit: in case it isn't obvious, this is for the Windows platforms.

5 Answers 5

14

I needed a simple, Windows/Posix solution to test if a user has root/admin privileges to the file system without installing an 3rd party solution. I understand there are vulnerabilities when relying on environment variables, but they suited my purpose. It might be possible to extend this approach to read/write the registry.

I tested this with Python 2.6/2.7 on WinXP, WinVista and Wine. If anyone knows this will not work on Pyton 3.x and/or Win7, please advise. Thanks.

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)
Sign up to request clarification or add additional context in comments.

3 Comments

This is the first good answer cause it's actually checking if the script has admin privileges instead of checking the account.
I'm using Windows 10 Pro 22H2. The has_admin script only works if the administrator account has accessed C:\Windows\Temp before and gained 'permanent' access. You can easily test test by temporarily adding a new administrator account and don't access C:\Windows\Temp before you run the script.
Any Linux hosts I tested has both USER and LOGNAME, but not USERNAME.
8

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 seems pywin32 does support Python 3.

1 Comment

15 years later there is no need for 3rd party modules like pywin32 anymore, just use: import ctypes; IS_ADMIN = ctypes.windll.shell32.IsUserAnAdmin()
4

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

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

I suggest ctypes since it comes standard in python now, and there is a good example of using CreateProcess with ctypes here.

Comments

1

Most straightforward way is try to change the key at the beginning, maybe to a stub value - if that fails, catch the error and tell the user.

1 Comment

Depending on the situation this may clobber the value of an existing key, in which case you might need to read it first, save that value, try to change it, and be sure to set it back if it succeeds. That's fine an all, until someone hits ctrl-c or the power goes out between the last two steps. It's an easy solution with difficult edge cases.
0

As of today, the best way is to combine a unixism with a windowism:

import os

# We don't want import errors for missing modules
try:
    import ctypes
except ImportError:
    pass

def is_admin():
    try:
        return os.getuid() == 0
    except AttributeError:
        return ctypes.windll.shell32.IsUserAnAdmin()

if (is_admin()): 
    print("You got admin rights!")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.