Sometimes, your Python script needs to perform actions that require administrator privileges, such as managing services, modifying system settings, or running tools like net session. On Windows, this typically involves triggering a UAC (User Account Control) prompt.
In this post, we'll walk through how to automatically elevate your Python script to admin, run privileged commands, and gracefully fall back when permissions are denied.
🧩 The Python Script
import ctypes
import sys
import subprocess
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def request_admin_privileges():
try:
result = ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, " ".join(sys.argv), None, 1
)
return result > 32 # Success if result > 32
except Exception as e:
print("Error:", str(e))
return False
# === Main Logic ===
if not is_admin():
success = request_admin_privileges()
if success:
print("Requested admin privileges. Relaunching...")
else:
print("Admin privilege request was denied.")
sys.exit()
else:
# Relaunched with admin rights
print("Running with admin privileges!")
# Example privileged command
subprocess.run("net session", shell=True)
input("Press Enter to exit...")
🔍 How It Works
- ctypes.windll.shell32.IsUserAnAdmin() checks whether the script is running as administrator.
- If not, ShellExecuteW(..., "runas", ...) relaunches the same script using UAC.
- Once elevated, the script re-enters from the top but now is_admin() will return True.
- ✅ Note: net session is a classic example of a command that only works if the script is elevated.
Top comments (0)