For those of us working in C#, in the Windows SDK there is a "UACDemo" application as a part of the "Cross Technology Samples". They find if the current user is an administrator using this method:
private bool IsAdministrator
{
get
{
WindowsIdentity wi = WindowsIdentity.GetCurrent();
WindowsPrincipal wp = new WindowsPrincipal(wi);
return wp.IsInRole(WindowsBuiltInRole.Administrator);
}
}
(Note: I refactored the original code to be a property, rather than an "if" statement)
As of 2017, an easy method to achieve this is the following:
import ctypes, sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
# Code of your program here
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
If you are using Python 2.x, then you should replace the last line for:
ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1)
Also note that if you converted you python script into an executable file (using tools like py2exe
, cx_freeze
, pyinstaller
) then you should use sys.argv[1:]
instead of sys.argv
in the fourth parameter.
Some of the advantages here are:
- No external libraries required. It only uses
ctypes
and sys
from standard library.
- Works on both Python 2 and Python 3.
- There is no need to modify the file resources nor creating a manifest file.
- If you don't add code below if/else statement, the code won't ever be executed twice.
- You can get the return value of the API call in the last line and take an action if it fails (code <= 32). Check possible return values here.
- You can change the display method of the spawned process modifying the sixth parameter.
Documentation for the underlying ShellExecute call is here.
Best Answer
This registry key should tell you:
Value
EnableLUA (DWORD)
1
enabled /0
or missing disabledBut that assumes you have the rights to read it.
Programmatically you can try to read the user's token and guess if it's an admin running with UAC enabled (see here). Not foolproof, but it may work.
The issue here is more of a "why do you need to know" - it has bearing on the answer. Really, there is no API because from a OS behavior point of view, what matters is if the user is an administrator or not - how they choose to protect themselves as admin is their problem.