简体   繁体   English

使用 python 执行 powershell 命令

[英]Execute powershell command using python

I want to execute power-shell command using my python script to find windows RDP event detail but it's not working.it shown error:我想使用我的 python 脚本执行 power-shell 命令来查找 windows RDP 事件详细信息,但它不起作用。它显示错误:

'C:\Windows\System32\powershell.exe' is an internal or external command, It is not recognized as an operable program or batch file. 'C:\Windows\System32\powershell.exe' 是内部或外部命令,它不被识别为可运行的程序或批处理文件。

PowerShell command: PowerShell 命令:

Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | Where-Object {$_.ID -eq "1149"} 

Here is my python code:这是我的 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)

Instead of using PowerShell, You can use pywin32 module to get the Windows events.您可以使用pywin32 模块来获取 Windows 事件,而不是使用 PowerShell。

If there is no specific reason to use PowerShell then you can achieve it by using following code snippet如果没有使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM