首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >以python管理员身份运行powershell

以python管理员身份运行powershell
EN

Stack Overflow用户
提问于 2022-07-28 12:45:08
回答 1查看 462关注 0票数 1

我有一个PowerShell脚本,如下所示:

代码语言:javascript
运行
复制
# Define time for report (default is 1 day)
$startDate = (get-date).AddDays(-10)

# Store successful logon events from security logs with the specified dates and workstation/IP in an array
# foreach ($DC in $DCs){
# $slogonevents = Get-Eventlog -LogName Security -ComputerName $DC.Hostname -after $startDate | where {$_.eventID -eq 4624 }
# }

$slogonevents = Get-Eventlog -LogName Security -after $startDate | where {$_.eventID -eq 4624 }

# Crawl through events; print all logon history with type, date/time, status, account name, computer and IP address if user logged on remotely

  $(foreach ($e in $slogonevents){
    # Logon Successful Events
    # Local (Logon Type 2)
    if (($e.EventID -eq 4624 ) -and ($e.ReplacementStrings[8] -eq 2)){
      write-host "Type: Local Logon`tDate: "$e.TimeGenerated "`tStatus: Success`tUser: "$e.ReplacementStrings[5] "`tWorkstation: "$e.ReplacementStrings[11]
    }
    # Remote (Logon Type 10)
    if (($e.EventID -eq 4624 ) -and ($e.ReplacementStrings[8] -eq 10)){
      write-host "Type: Remote Logon`tDate: "$e.TimeGenerated "`tStatus: Success`tUser: "$e.ReplacementStrings[5] "`tWorkstation: "$e.ReplacementStrings[11] "`tIP Address: "$e.ReplacementStrings[18]
    }
}) *>&1 > D:\Cyber_security\Python\test.txt

我想从python运行这个脚本。这个脚本保存在我的D drive.My python脚本中:

代码语言:javascript
运行
复制
import subprocess, sys

p = subprocess.Popen(["powershell.exe", 
              "D:\Cyber_security\Python\login.ps1"], 
              stdout=sys.stdout)
p.communicate()

但不起作用。我需要作为管理员运行powershell,但我不知道如何运行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-28 14:58:54

您需要嵌套powershell.exe调用:

  • 使用Start-Process调用PowerShell的-Verb RunAs cmdlet的外部调用,它允许运行任何具有海拔的可执行文件。
  • 由于您想要运行的是一个.ps1脚本,所以必须通过powershell.exe ( Windows PowerShell CLI )调用它,就像在您自己的尝试中一样,但您需要显式地合并一个Set-Location调用,以确保脚本在相同的工作dir中运行。作为调用方(C:\Windows\System32是PowerShell中使用Start-Process -Verb RunAs时的缺省值)。
代码语言:javascript
运行
复制
- If you don't need this, or if you're using `pwsh.exe`, the CLI of the cross-platform [_PowerShell (Core) 7+_](https://github.com/PowerShell/PowerShell/blob/master/README.md) edition (which now retains the working dir. by default), the inner call can be simplified to:
- `powershell.exe -Args '-noprofile -file D:\Cyber_security\Python\login.ps1'`
代码语言:javascript
运行
复制
# See bottom section if you also want to get the exit code of 
# the elevated process.
p = subprocess.Popen(
  [
    "powershell.exe", 
    "-noprofile", "-c",
    r"""
    Start-Process -Verb RunAs -Wait powershell.exe -Args "
      -noprofile -c Set-Location \`"$PWD\`"; & D:\Cyber_security\Python\login.ps1
      "
    """
  ],
  stdout=sys.stdout
)
p.communicate()

注意:

  • 运行具有高度的进程:
代码语言:javascript
运行
复制
- involves an interactive UAC confirmation / credentials prompt that cannot be bypassed (unless UAC is turned off, which would be ill-advised)
- invariably runs in a _new window_.
- prevents _direct_ capture of the elevated process' output streams; you'll have to redirect to (temporary) _files_ instead, which you can do with `Start-Process`' 

-RedirectStandardOutput / -RedirectStandardError参数

  • 添加了CLI参数-noprofile-c-noprofile禁止加载PowerShell的配置文件-c (-Command)显式地指示要执行的PowerShell命令。
  • -Wait被添加到上面的Start-Process调用中,以便使外部powershell.exe调用在继续之前等待提升的进程退出。
  • 启动提升过程并不严格需要powershell.exe + Start-Process -Verb RunAs,但这是最方便的选择。
代码语言:javascript
运行
复制
- A Python-based solution is possible, but involves fairly complex use of the WinAPI - see [this blog post](https://yeahexp.com/how-to-run-a-subprocess-with-admin-permission/)
- Note that while you can technically use `runas.exe /user:Administrator` utility to create an elevated session, doing so (a) only works with precisely that account, i.e. the built-in account named `Adminstrator`, and that account is often disabled in practice (it is disabled by default).
  • 另一种方法是修改.ps1文件,以便按需自举(或使用帮助器.ps1文件进行此操作)-请参阅这个答案

变体,它还获取提升进程的退出代码:

如果您的.ps1脚本使用exit语句来故意报告一个(进程)退出代码,该退出代码标志着成功还是失败,并且您希望查询退出代码,则需要做更多的工作:

  • Start-Process -PassThru开关输出一个表示新启动进程的进程信息对象,其.ExitCode属性报告进程退出代码(终止后)。
  • 由于-c / -Command CLI参数的工作方式,内部powershell.exe调用必须显式地使用exit $LASTEXITCODE将脚本的退出代码中继为提升的进程退出代码。
代码语言:javascript
运行
复制
p = subprocess.Popen(
  [
    "powershell.exe", 
    "-noprofile", "-c",
    r"""
    exit (
      Start-Process -Verb RunAs -PassThru -Wait powershell.exe -Args "
        -noprofile -c Set-Location \`"$PWD\`"; & C:\Users\jdoe\Desktop\pg\pg.ps1; exit `$LASTEXITCODE
      "
    ).ExitCode
    """
  ],
  stdout=sys.stdout
)
p.communicate()

print('Terminated with exit code ' + str(p.returncode))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73153170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档