0

I want to extract a zip archive to "C:\\" (just for testing purpose). Therefore I need admin rights, so I am trying to elevate the current user to get admin rights.

if __name__ == "__main__":
    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)
        main()

The invoking message from UAC is comming as it should but when I want to extract the zip I am still getting "IOError: [Errno 13] Permission denied".

What am I doing wrong here?

1 Answers1

2

It looks like your goal is to re-execute the same script with new permissions.

The way you are doing it now executes the script again in a new process, which then check that it has the "asadmin" flag, and immediately exits, because there is nothing else to do there. Then the original process (without elevated permissions) executes main.

You probably want to put the call to main in an else block so it gets executed only when asadmin is set:

if __name__ == "__main__":
    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)
    else:
        main()

Also, you may want to find a better way to do the permissions check. If you run this script as admin, it will still need to re-execute itself in order to set the "asadmin" flag. And if you run as a regular user and set "asadmin" manually, the script doesn't work. There's probably an API for this somewhere.

zstewart
  • 2,093
  • 12
  • 24
  • Hmm I changed the code like you did, but now my program exits right after the UAC with exit code 0? – User 90234 Feb 11 '17 at 09:48
  • Well, I don't know if shell.ShellExecuteEx is a blocking call. If it is non-blocking, then your original run of the script would exit immediately, and a new process with the same script would continue running separately, doing whatever is in main. See also, this question: http://stackoverflow.com/questions/130763 – zstewart Feb 11 '17 at 14:29