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:

'C:\Windows\System32\powershell.exe' is an internal or external command, It is not recognized as an operable program or batch file.

power-shell command:

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

Here is my python code:

import subprocess

subprocess.call('C:\Windows\System32\powershell.exe Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" | Where-Object {$_.ID -eq "1149"}', shell=True)

1 answer

  • answered 2020-06-02 11:26 CodeRunner

    Instead of using PowerShell, You can use pywin32 module to get the Windows events.

    If there is no specific reason to use PowerShell then you can achieve it by using following code snippet

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