jborean93 / pypsrp

PowerShell Remoting Protocol for Python
MIT License
324 stars 49 forks source link

How to output the return value in real time #174

Open Centeryuhao opened 1 year ago

Centeryuhao commented 1 year ago

I try to use ping command Need to wait for the execution to end before returning the result How to return in real time? tks

   client = Client(server='xxxx', username='xxxx', password='xxxx',ssl=False, connection_timeout=2)
   output, streams, had_errors = client.execute_ps("ping github.com")
   print(streams)
   print(output)

Actually, I need to call other scripts and return values in real time.

Using the ping command as an example

bchen290 commented 10 months ago

Hey, I was able to put together a hacky solution for this

with wsman, RunspacePool(wsman) as pool:
    ps = PowerShell(pool)
    ps.add_script(command)
    ps.add_cmdlet("Out-String").add_parameter("Stream")
    ps.begin_invoke()  # execute process in the background
    while ps.state == PSInvocationState.RUNNING:
        current_output = [str(s) for s in ps.output]
        if current_output:
            print("\n".join(current_output))
        ps.output = []
        ps.poll_invoke()  # update the output streams
jborean93 commented 10 months ago

Essentially the above, the old pypsrp API only allows intermediate output with poll_invoke(). The new psrp API which is still in beta is a lot more flexible and can run things in a separate thread of asyncio context to do it a bit more easily.