通过 Python 启用 Windows 功能不会让 DISM 具有提升的访问权限,即使在让 Python 通过功能获得提升的访问权限之后也是如此

Enabling Windows Features through Python won't let DISM have elevated access even after letting Python get elevated access through functions

我正在尝试通过函数 Python 启用 Windows 功能。这是我使用过的脚本:

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')

我可以通过UAC提示,但是当通过winfeatures到达功能部分时,它会显示:


Error: 740

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

我假设 DISM 没有获得提升的访问权限。任何修复?

这个:

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

第一行将启动一个新进程。第二行执行但它仍然是 运行 as non-admin:

我想你想要这个:

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

然后在你的其他文件中:

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