![](/img/trans.png)
[英]Execute Powershell Command remotely and print the output using wmi python
[英]Execute powershell command using python
我想使用我的 python 腳本執行 power-shell 命令來查找 windows RDP 事件詳細信息,但它不起作用。它顯示錯誤:
'C:\Windows\System32\powershell.exe' 是內部或外部命令,它不被識別為可運行的程序或批處理文件。
PowerShell 命令:
Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | Where-Object {$_.ID -eq "1149"}
這是我的 python 代碼:
import subprocess
subprocess.call('C:\Windows\System32\powershell.exe Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | Where-Object {$_.ID -eq "1149"}', shell=True)
您可以使用pywin32 模塊來獲取 Windows 事件,而不是使用 PowerShell。
如果沒有使用 PowerShell 的具體原因,那么您可以使用以下代碼片段來實現
import win32evtlog # install pywin32 module
server = 'localhost' # target computer to get event logs
logtype = 'Microsoft-Windows-TerminalServices-RemoteConnectionManager' # 'Application' # 'Security'
hand = win32evtlog.OpenEventLog(server,logtype)
flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
total = win32evtlog.GetNumberOfEventLogRecords(hand)
while True:
events = win32evtlog.ReadEventLog(hand, flags,0)
if events:
for event in events:
if "Microsoft-Windows-Terminal-Services-RemoteConnectionManager" in event.SourceName:
print ('Event Category:', event.EventCategory)
print ('Time Generated:', event.TimeGenerated)
print ('Source Name:', event.SourceName)
print ('Event ID:', event.EventID)
print ('Event Type:', event.EventType)
data = event.StringInserts
if data:
print ('Event Data:')
for msg in data:
print (msg)
print
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.