2

I need my python script to have elevated UAC privileges. I have tried again and again and can NOT figure it out.

This is my code right now:

from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
import win32process, win32event
import win32con
from ntsecuritycon import *

ASADMIN = 'asadmin'

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    ShellExecuteEx(fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                    lpVerb="runas",
                    lpFile=sys.executable,
                    lpParameters=params,
                    nShow=win32con.SW_SHOW)
    sys.exit(0)

Now, the information I have so far is that this will run without errors, and it does reopen itself. The reopened script returns

["c:\\users\\justin\\UAC.py", "asadmin"]

for

sys.argv

, but it still won't let me perform admin tasks.

Although help with fixing this code would be optimal, I'm also ready to try anything else that works, thanks!

user1845265
  • 21
  • 1
  • 2
  • 1
    Possible duplicate of http://stackoverflow.com/questions/130763/request-uac-elevation-from-within-a-python-script – Bakuriu Nov 22 '12 at 14:12
  • I suppose, but the answer doesn't really help me in writing the code. – user1845265 Nov 22 '12 at 14:26
  • Have you tried setting your actual python.exe to run with administrator privileges? Then anything it runs will also have those permissions. The program itself won't be able to cause itself to run with admin as what would be the point of UAC if it could? – Paul Collingwood Nov 22 '12 at 15:00

1 Answers1

1

Use the following:

import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    print("I am root now.")
theroyakash
  • 143
  • 1
  • 4