Search code examples
pythonpython-3.xelevated-privilegesadmin-rights

Run python app as admin without prompting for admin page


Can we run python app as admin by storing the admin credentials in python code and when python app needs admin rights it should use the admin credentials stored in it's code and run with admin rights. But it should not prompt for admin page.

Let the admin credentials be Username: admin pass: admin@123


Solution

  • This is the code I successfully used on WinXP and Win7 and I see no reason why it should not work on Win10.

    global userH
    userH = None
    def try_login(name, domain, password):
        global userH
        try:
            logging.info("Trying to login as: %s/%s" % (domain, name))
            userH = win32security.LogonUser(name, domain, password,
                    win32security.LOGON32_LOGON_INTERACTIVE,
                    win32security.LOGON32_PROVIDER_DEFAULT)
            if None!=userH:
                win32security.ImpersonateLoggedOnUser(userH)
                logging.info("Logged in: %s/%s" % (domain, name))
                return True
        except:
            logging.exception("Windows login")
            if userH:
                try:
                    win32api.CloseHandle(userH)
                except:
                    pass
            userH = None
        return False
    
    def logout():
        if userH:
            try:
                win32security.RevertToSelf()
                win32api.CloseHandle(userH)
            except:
                pass