Run python app as admin without prompting for admin page

457 Views Asked by At

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

1

There are 1 best solutions below

1
Petr Blahos On BEST ANSWER

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