Last active
March 22, 2024 21:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!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, ) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
py2 -> py3:
unicode
withstr
raw_input
withinput