Using Python to check if the application is running as an Administrator

The source below checks if the application is running with administrator privileges. Also, this script works on both Unis and Windows system… well, almost all Windows Systems… it doesnt work on WindowsXP… sorry.  🙁

import ctypes, os

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

This code first tries to check it’s running as admin in a Unix system, if that fails, an exception is happens and the script assumes you’re on a Windows System.

The function will return true or false, depending if you’re an admin or not…

Here’s how to use it:

if isAdmin():
    print("Admin! Oh yeah!")
else:
    print("Just a mortal!")

Reference:

The following two tabs change content below.
Software Architect and Backend Developer (almost Fullstack), I usually work with C#, PowerShell, Python, Golang, bash and Unity (this one is more for a hobby). I'm always looking for something new to learn, adding new tools to my utility belt.
Posted in Dev, Python and tagged , , , .