Skip to content

Instantly share code, notes, and snippets.

@HatScripts
Forked from GaryLee/RunAsAdmin.py
Last active September 18, 2020 15:41
Show Gist options
  • Save HatScripts/2e90dc41b692d7b100643836ca974faf to your computer and use it in GitHub Desktop.
Save HatScripts/2e90dc41b692d7b100643836ca974faf 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.
# Based on Gary Lee's code:
# https://gist.github.com/GaryLee/d1cf2089c3a515691919
# https://stackoverflow.com/a/33856172/2203482
def run_as_admin(argv=None):
import ctypes
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
import sys
if argv is None:
argv = sys.argv
arguments = argv[1:] if hasattr(sys, "_MEIPASS") else argv
argument_line = " ".join(str(arg) for arg in arguments)
executable = str(sys.executable)
# Elevating to admin privileges...
ret = shell32.ShellExecuteW(None, "runas", executable, argument_line, None, 1)
if int(ret) <= 32:
raise IOError(f"Error(ret={ret}): Cannot elevate admin privileges.")
else:
return False
if __name__ == "__main__":
if run_as_admin():
# Your code requiring admin privileges goes here, for example:
from pathlib import Path
Path("path/to/link").symlink_to(Path("path/to/target"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment