Home > Mobile >  Enabling Windows Features through Python won't let DISM have elevated access even after letting
Enabling Windows Features through Python won't let DISM have elevated access even after letting

Time:03-18

I'm trying to enable Windows Features through Python through functions. Here's the scripts that I've used:

UAC.py:

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

winfeatures.py

def install(feature):
    packageName = feature
    import os
    os.system("cmd /k dism /online /Enable-Feature /FeatureName:"   packageName   "/All")

if __name__ == "__main__":
    install()

enablefeatures.py:

import UAC
import winfeatures
import os

UAC.gainadminaccess()
winfeatures.install('VirtualMachinePlatform')

I'm OK with passing the UAC prompt, but when arriving at the feature part through winfeatures, it will show:


Error: 740

Elevated permissions are required to run DISM. 
Use an elevated command prompt to complete these tasks.

which I assume that DISM didn't get elevated access. Any fix?

CodePudding user response:

This:

UAC.gainadminaccess()
winfeatures.install('VirtualMachinePlatform')

The first line will launch a new process. The second line executes but it is still running as non-admin:

I think you want this instead:

def gainadminaccess():
    import os
    import sys
    import win32com.shell.shell as shell
    ASADMIN = 'asadmin'

    isAdmin = sys.argv[-1] == ASADMIN

    if not isAdmin:
        script = os.path.abspath(sys.argv[0])
        params = ' '.join([script]   sys.argv[1:]   [ASADMIN])
        shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    
    return isAdmin # returns true if this script is already running as admin

Then in your other file:

if UAC.gainadminaccess():
    winfeatures.install('VirtualMachinePlatform')
  • Related