Requesting Privileges in Windows with python

Asked

Viewed 58 times

2

I have my python script, but, I need Administrator privileges to run a bug-free function ex.: delete a folder.

How do I make my script ask for Windows privileges.

  • https://stackoverflow.com/questions/130763/request-uac-elevation-from-within-a-python-script. what do you think?

1 answer

2

You cannot change the privileges after launching a run on Windows. What you need is to ensure that the application runs with administrator privileges and not as a normal user.

What you can do is check the privileges at the time you start running the program and, if they are too low, ask the user to launch it again, now as an administrator, or do as the program itself automatically restarts, but with greater privileges through runas.

import ctypes

if not ctypes.windll.shell32.IsUserAnAdmin():
    print('Sem privilégios suficientes. Reiniciando...')
    import sys
    ctypes.windll.shell32.ShellExecuteW(
        None, 'runas', sys.executable, ' '.join(sys.argv), None, None)
    exit(0)
else:
    print('Privilégios superiores garantidos')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.