Created
September 16, 2021 14:14
-
-
Save jrialland/a430a3579c64811c817afd86a55ed94a to your computer and use it in GitHub Desktop.
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
import ctypes, subprocess, sys | |
def elevate(): | |
if ctypes.windll.shell32.IsUserAnAdmin(): | |
return | |
else: | |
class ShellExecuteInfo(ctypes.Structure): | |
_fields_ = [('cbSize', ctypes.wintypes.DWORD), | |
('fMask', ctypes.c_ulong), | |
('hwnd', ctypes.wintypes.HWND), | |
('lpVerb', ctypes.c_char_p), | |
('lpFile', ctypes.c_char_p), | |
('lpParameters', ctypes.c_char_p), | |
('lpDirectory', ctypes.c_char_p), | |
('nShow', ctypes.c_int), | |
('hInstApp', ctypes.wintypes.HINSTANCE), | |
('lpIDList', ctypes.c_void_p), | |
('lpClass', ctypes.c_char_p), | |
('hKeyClass', ctypes.wintypes.HKEY), | |
('dwHotKey', ctypes.wintypes.DWORD), | |
('hIcon', ctypes.wintypes.HANDLE), | |
('hProcess', ctypes.wintypes.HANDLE)] | |
def __init__(self, **kw): | |
ctypes.Structure.__init__(self) | |
self.cbSize = ctypes.sizeof(self) | |
for field_name, field_value in kw.items(): | |
setattr(self, field_name, field_value) | |
ShellExecuteEx = ctypes.windll.Shell32.ShellExecuteExA | |
ShellExecuteEx.argtypes = (ctypes.POINTER(ShellExecuteInfo), ) | |
ShellExecuteEx.restype = ctypes.wintypes.BOOL | |
SEE_MASK_NOCLOSEPROCESS = 0x00000040 | |
SW_SHOW = 5 | |
execute_info = ShellExecuteInfo( | |
fMask=SEE_MASK_NOCLOSEPROCESS, | |
hwnd = None, | |
lpVerb = b'runas', | |
lpFile = sys.executable.encode('cp1252'), | |
lpParameters = subprocess.list2cmdline(sys.argv).encode('cp1252'), | |
lpDirectory = None, | |
nShow = SW_SHOW | |
) | |
if not ShellExecuteEx(ctypes.byref(execute_info)): | |
raise ctypes.WinError() | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment