Menu Close

How to run script with elevated privilege on Windows?

Sometimes, we want to run script with elevated privilege on Windows.

In this article, we’ll look at how to run script with elevated privilege on Windows.

How to run script with elevated privilege on Windows?

To run script with elevated privilege on Windows, we call shell.ShellExecuteEx to run the runas command.

For instance, we write

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)
    sys.exit(0)
with open("somefilename.txt", "w") as out:
    print(out)

to call shell.ShellExecuteEx with the lpVerb argument set to 'runas' to run the runas command.

We run runas with the program name and 'asadmin' to run our command as admin.

Once we’re done we call sys.exit to exit the program.

Conclusion

To run script with elevated privilege on Windows, we call shell.ShellExecuteEx to run the runas command.

Posted in Python, Python Answers