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.
import ctypes, os
try:
is_admin = os.getuid() == 0
except AttributeError:
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
print is_admin
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With