[英]How to send commands to Powershell from Python as an administrator?
[英]run powershell as administrator from python
我有一個 PowerShell 腳本,如下所示:
# 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 盤中。我的 python 腳本是:
import subprocess, sys
p = subprocess.Popen(["powershell.exe",
"D:\Cyber_security\Python\login.ps1"],
stdout=sys.stdout)
p.communicate()
但它不起作用。 我需要以管理員身份運行 powershell 但我不知道該怎么做。
您需要嵌套powershell.exe
調用:
使用-Verb RunAs
調用 PowerShell 的Start-Process
cmdlet 的外部調用,它允許運行具有提升的任何可執行文件。
由於您要使用提升運行的是.ps1
腳本,因此必須通過powershell.exe
、 Windows PowerShell CLI調用來調用它,以確保明確地包含一個Set-Location
調用,如在您自己的嘗試中那樣,腳本在同一個工作目錄中運行。 作為調用者( C:\Windows\System32
是 Windows PowerShell 中使用Start-Process -Verb RunAs
時的默認值)。
pwsh.exe
,跨平台PowerShell (Core) 7+版本的 CLI(現在默認保留工作目錄),內部調用可以簡化至:powershell.exe -Args '-noprofile -file D:\Cyber_security\Python\login.ps1'
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()
筆記:
運行具有高度的進程:
Start-Process
'-RedirectStandardOutput
/ -RedirectStandardError
參數。 添加了 CLI 參數-noprofile
和-c
: -noprofile
禁止加載 PowerShell 的配置文件,並且-c
( -Command
) 明確指示以下是要執行的 PowerShell 命令。
-Wait
已添加到上面的Start-Process
調用中,以使外部powershell.exe
調用等待提升的進程退出后再繼續。
您並不嚴格需要powershell.exe
+ Start-Process -Verb RunAs
來啟動提升的進程,但它是最方便的選項。
runas.exe /user:Administrator
實用程序來創建提升的 session,但這樣做 (a) 僅適用於該帳戶,即名為Adminstrator
的內置帳戶,並且該帳戶通常在實踐中被禁用(默認情況下禁用)。 另一種方法是修改.ps1
文件以按需自我提升(或使用輔助.ps1
文件執行此操作) - 請參閱此答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.