Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - checking if a user has administrator privileges

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.

like image 744
Kefka Avatar asked Nov 29 '22 11:11

Kefka


2 Answers

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)
like image 169
tahoar Avatar answered Dec 06 '22 09:12

tahoar


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.

like image 40
Alex Martelli Avatar answered Dec 06 '22 09:12

Alex Martelli