Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-platform way to check admin rights in a Python script under Windows?

Is there any cross-platform way to check that my Python script is executed with admin rights? Unfortunately, os.getuid() is UNIX-only and is not available under Windows.

like image 724
grigoryvp Avatar asked Jun 22 '09 10:06

grigoryvp


3 Answers

import ctypes, os
try:
 is_admin = os.getuid() == 0
except AttributeError:
 is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0

print is_admin
like image 195
grigoryvp Avatar answered Oct 18 '22 23:10

grigoryvp


Here's a utility function I created from the accepted answer:

import os
import ctypes

class AdminStateUnknownError(Exception):
    """Cannot determine whether the user is an admin."""
    pass


def is_user_admin():
    # type: () -> bool
    """Return True if user has admin privileges.

    Raises:
        AdminStateUnknownError if user privileges cannot be determined.
    """
    try:
        return os.getuid() == 0
    except AttributeError:
        pass
    try:
        return ctypes.windll.shell32.IsUserAnAdmin() == 1
    except AttributeError:
        raise AdminStateUnknownError
like image 11
Bryce Guinta Avatar answered Oct 18 '22 23:10

Bryce Guinta


Try doing whatever you need admin rights for, and check for failure.

This will only work for some things though, what are you trying to do?

like image 3
cobbal Avatar answered Oct 18 '22 23:10

cobbal