Skip to content

Instantly share code, notes, and snippets.

@GaryLee
Last active March 22, 2024 21:52
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save GaryLee/d1cf2089c3a515691919 to your computer and use it in GitHub Desktop.
Save GaryLee/d1cf2089c3a515691919 to your computer and use it in GitHub Desktop.
Elevate the privilege to Admin. Support both python script and pyinstaller wrapped program. Need ctypes only.
#!python
# coding: utf-8
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, )
@hamaney
Copy link

hamaney commented Aug 18, 2019

py2 -> py3:

  • replace unicode with str
  • replace raw_input with input

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment