Skip to content

Instantly share code, notes, and snippets.

@Devligue
Last active April 20, 2024 16:24
Show Gist options
  • Save Devligue/e70df351698ded87d4eefd66983fab4d to your computer and use it in GitHub Desktop.
Save Devligue/e70df351698ded87d4eefd66983fab4d to your computer and use it in GitHub Desktop.
Collection of Python code snippets usefull to deal with admin privilages on Windows
#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4
# (C) COPYRIGHT © Preston Landers 2010
# Released under the same license as Python 2.6.5
import sys
import os
import traceback
import types
def isUserAdmin():
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print "Admin check failed, assuming not an admin."
return False
elif os.name == 'posix':
# Check for root on Posix
return os.getuid() == 0
else:
raise RuntimeError, "Unsupported operating system for this module: %s" % (os.name,)
def runAsAdmin(cmdLine=None, wait=True):
if os.name != 'nt':
raise RuntimeError, "This function is only implemented on Windows."
import win32api
import win32con
import win32event
import win32process
from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
python_exe = sys.executable
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif type(cmdLine) not in (types.TupleType, types.ListType):
raise ValueError, "cmdLine is not a sequence."
cmd = '"%s"' % (cmdLine[0],)
# XXX TODO: isn't there a function or something we can call to massage
# command line params?
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
cmdDir = ''
showCmd = win32con.SW_SHOWNORMAL
#showCmd = win32con.SW_HIDE
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
# print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = None
return rc
def test():
rc = 0
if not isUserAdmin():
print "You're not an admin.", os.getpid(), "params: ", sys.argv
#rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
rc = runAsAdmin()
else:
print "You are an admin!", os.getpid(), "params: ", sys.argv
rc = 0
x = raw_input('Press Enter to exit.')
return rc
if __name__ == "__main__":
sys.exit(test())
"""Contains helpers to elevate the user rights under Windows"""
# https://github.com/0xLeon/py-elevate
from __future__ import absolute_import
from __future__ import unicode_literals
import ctypes
import sys
from builtins import str as text
__version__ = '0.0.0'
def elevate(args=None):
"""Tries to rerun the current script with admin rights"""
if not is_admin():
if args is None:
args = sys.argv
runas(sys.executable, args)
return False
return True
def runas(executable, args=None):
params = []
if args is not None:
for arg in args:
if '"' in arg:
arg = '"' + arg.replace('"', r'\"') + '"'
elif ' ' in arg:
arg = '"' + arg + '"'
params.append(arg)
res = ctypes.windll.shell32.ShellExecuteW(None, "runas", text(executable), text(' '.join(params)), None, 1)
if res <= 32:
raise WindowsError("ShellExecute returned error code %d" % res)
def is_admin():
"""Checks if the script is run with full admin rights"""
return ctypes.windll.shell32.IsUserAnAdmin() == 1
# https://github.com/daigotanaka/pyelevate/blob/master/elevate.py
import sys
import win32event
from win32com.shell import shell
def elevate(command, param="", wait=False):
"""
Execute a shell command with elevated rights when the current
user can have the privilge.
Deisgned to be used with Windows Vista, 7 and 8.
It also works on Windows XP although it is not necessary on many
occasions.
It may pops User Access Control dialog to confirm the elevation.
"""
# SEE_MASK_NOASYNC(0x00000100) + SEE_MASK_NOCLOSEPROCESS(0x00000040)
f_mask = 256 + 64 if wait else 0
dict = shell.ShellExecuteEx(
fMask=f_mask,
hwnd=None,
lpVerb="runas",
lpFile=command,
lpParameters=param,
lpDirectory=""
)
if not wait:
return dict
hh = dict["hProcess"]
ret = win32event.WaitForSingleObject(hh, -1)
return ret
if __name__ == "__main__":
argv = sys.argv
command = argv[1]
param = " ".join(argv[2:]) if len(argv) > 1 else None
elevate(command, param)
#!python
# coding: utf-8
# by GaryLee
# https://gist.github.com/GaryLee/d1cf2089c3a515691919
import sys
import ctypes
def run_as_admin(argv=None, debug=False):
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
if argv is None:
argv = sys.argv
if hasattr(sys, '_MEIPASS'):
# Support pyinstaller wrapped program.
arguments = map(unicode, argv[1:])
else:
arguments = map(unicode, argv)
argument_line = u' '.join(arguments)
executable = unicode(sys.executable)
if debug:
print 'Command line: ', executable, argument_line
ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
if int(ret) <= 32:
return False
return None
if __name__ == '__main__':
ret = run_as_admin()
if ret is True:
print 'I have admin privilege.'
raw_input('Press ENTER to exit.')
elif ret is None:
print 'I am elevating to admin privilege.'
raw_input('Press ENTER to exit.')
else:
print 'Error(ret=%d): cannot elevate privilege.' % (ret, )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment