使用subprocess.run在python中以管理员身份运行进程

15

是否有在Python中,向subprocess.run函数传递runas=True参数的方法? 我想要以管理员身份(提升)运行一个进程。谢谢回答 :)

编辑:使用Windows操作系统。

4个回答

23

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

2
请注意,这仅适用于内置的“管理员”用户帐户,而不适用于通常属于“管理员”组的用户。实际上,出于安全原因,内置的“管理员”帐户经常被禁用。 - mklement0

2
有三种方法:
  1. 使用如此答案所示的runas。这种方法的缺点是它使用管理员帐户而不是当前用户的管理员权限。如果您计划将软件部署给用户,则无法很好地工作。
  2. 使用如此问题所讨论的ShellExecute来启动子进程。缺点是您将无法使用stdin / stdout / stderr。
  3. 使用JetBrains的WinElevator(签名的launcher.exe和elevator.exe可在此处找到)。这种方法的缺点是您需要提供两个额外的 ~150kb 二进制文件,优点是您可以与stdin / stdout / stderr交互。

2

如果您想以管理员权限运行相同用户的命令

请参考以下解决方案:

os.system(r'''
Powershell -Command "& { Start-Process \"notepad.exe\"
 -ArgumentList @(\"C:\\Windows\\System32\\drivers\\etc\\hosts\")
 -Verb RunAs } " '''

原始答案可在此找到:https://superuser.com/a/753600/1088510


-3

正如其他人建议的那样,您可以使用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 }
}

抱歉,但是原帖的作者正在寻找一个Python解决方案。 - PKCS12
抱歉,但是原帖的作者正在寻找一个Python解决方案。 - undefined
@PKCS12 我的意思是你可以从Python中调用PowerShell,然后再以提升的权限运行另一个可执行文件。 - Geordie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接