是否有在Python中,向subprocess.run
函数传递runas=True
参数的方法? 我想要以管理员身份(提升)运行一个进程。谢谢回答 :)
编辑:使用Windows操作系统。
是否有在Python中,向subprocess.run
函数传递runas=True
参数的方法? 我想要以管理员身份(提升)运行一个进程。谢谢回答 :)
编辑:使用Windows操作系统。
Windows 有一个命令行实用程序 "Run as",可用于
runas [{/profile | /noprofile}] [/env] [{/netonly | /savecred}] [/smartcard] [/showtrustlevels] [/trustlevel] /user:<UserAccountName> "<ProgramName> <PathToProgramFile>"
更多信息请参见 https://technet.microsoft.com/en-us/library/cc771525.aspx
您可以在以下代码中使用此功能。
import subprocess as sp
prog = sp.Popen(['runas', '/noprofile', '/user:Administrator', 'NeedsAdminPrivilege.exe'],stdin=sp.PIPE)
prog.stdin.write('password')
prog.communicate()
runas
。这种方法的缺点是它使用管理员帐户而不是当前用户的管理员权限。如果您计划将软件部署给用户,则无法很好地工作。ShellExecute
来启动子进程。缺点是您将无法使用stdin / stdout / stderr。WinElevator
(签名的launcher.exe和elevator.exe可在此处找到)。这种方法的缺点是您需要提供两个额外的 ~150kb 二进制文件,优点是您可以与stdin / stdout / stderr交互。如果您想以管理员权限运行相同用户的命令
请参考以下解决方案:
os.system(r'''
Powershell -Command "& { Start-Process \"notepad.exe\"
-ArgumentList @(\"C:\\Windows\\System32\\drivers\\etc\\hosts\")
-Verb RunAs } " '''
原始答案可在此找到:https://superuser.com/a/753600/1088510
正如其他人建议的那样,您可以使用PowerShell实现这一点。以下是我使用的PS函数,用于升级到管理员权限:
# ========================================= Admin Rights =======================================================
# Usage: asAdmin $PSCommandPath
function asAdmin
{
[string]$cmdPath = $args[0]
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$cmdPath`"" -Verb RunAs; exit }
}
#-noexit
function asAdminWithSTA
{
[string]$cmdPath = $args[0]
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-sta -NoProfile -ExecutionPolicy Bypass -File `"$cmdPath`"" -Verb RunAs; exit }
}