系统相关
首页 > 系统相关> > python 执行需要管理员权限的命令(Windows)

python 执行需要管理员权限的命令(Windows)

作者:互联网

由于Windows存在管理员权限限制,执行需管理员权限的命令时会出错,
有两种方案,
1.采用python调用vbs文件,vbs调用bat文件
2.采用提供弹出用户管理员权限方式让用户确认

1.采用python调用vbs文件,vbs调用bat文件

vbs文件

cwd = CreateObject("Scripting.FileSystemObject").GetFile(Wscript.ScriptFullName).ParentFolder.Path
path = cwd & "\cmd.bat"
Set shell = CreateObject("Shell.Application")
shell.ShellExecute path,"","","runas",0  ' 0代表不显示cmd命令窗口,1代表显示cmd命令行1窗口
WScript.Quit

详细vbs 执行见此处:vbs ShellExecute命令

bat文件

bat一般为空,主要为执行python时自动写入

python文件

import os
import subprocess
 
CMD_BAT = os.path.join(os.path.dirname(__file__), "cmd.bat")
VBS_PATH = os.path.join(os.path.dirname(__file__), "shell.vbs")

def runAdmin(cmd):
    """
    exec command with administrator
    :param: cmd: command requiring administrator 
    """
    try:
    	# 将命令写入bat文件
        with open(CMD_BAT, "w") as f:
            f.write(cmd)
        # 执行vbs文件
        vbs_command = "wscript {}".format(VBS_PATH)
        print(f"vbs_command:{vbs_command}")
        sp = subprocess.Popen(
            vbs_command,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        print("[PID]: %s[cmd]: %s" % (sp.pid, cmd))
    except Exception as e:
        print(f"exec vbs fail:{e}")

if __name__ == "__main__":
    command = "@powershell -NoProfile -ExecutionPolicy Bypass -Command \"iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))\" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\\bin\nchoco install virtualbox -y\n"
    runAdmin(command)

2.采用提供弹出用户管理员权限方式让用户确认

直接将runAdminCmdDecorator装饰在需要管理员权限执行的函数上即可

import os, sys, ctypes
from win32comext.shell.shell import ShellExecuteEx
from functools import wraps

def is_user_admin():
    """
    检查admin
    """
    return ctypes.windll.shell32.IsUserAnAdmin()

def run_as_admin():
    """ 
    弹出管理员运行弹窗 
    """
    script = os.path.abspath(sys.argv[0])
    print(f"script:{script}")
    args = ' '.join(sys.argv[1:]) if len(sys.argv) > 1 else ''
    ShellExecuteEx(lpFile=sys.executable, lpParameters=f"{script} {args}",
                   nShow=1, lpVerb='runas')
    return  

def runAdminCmdDecorator(func):
    @wraps(func)
    def inner(*args, **kwargs):
        if not is_user_admin():
            run_as_admin()
        else:
            func(*args, **kwargs)
    return inner

标签:__,bat,python,cmd,vbs,Windows,管理员,path,command
来源: https://www.cnblogs.com/xy-bot/p/16320045.html