Radhey Patel
Radhey Patel

Reputation: 5

How to not wait for the output of the remote execution?

I am using pysftp for remote execution, and the thing is that I don't want to wait for the output of the remote execution, I just want to start the execution and be done with it.

import pysftp as sftp
cnopts = sftp.CnOpts()
cnopts.hostkeys = None
handle = sftp.Connection('10.0.2.10',username='kali', password='root', cnopts=cnopts)
handle.execute('/tmp/doThis')
handle.exeute('/tmp/doThat')

Now the thing is that the script is waiting for doThis to get over and then it start with doThat. I tried using '&', but it has no affect. Is there someway of doing this, or is it not possible?

Upvotes: 0

Views: 261

Answers (2)

Parvathirajan Natarajan
Parvathirajan Natarajan

Reputation: 1305

Why don't you try the threading concept?

import pysftp as sftp
from threading import Thread
cnopts = sftp.CnOpts()
cnopts.hostkeys = None
handle = sftp.Connection('10.0.2.10',username='kali', password='root', cnopts=cnopts)

def exec(cmd):
    #handle will be taken from the prev declaration
    handle.execute(cmd)

list_cmds = ['/tmp/doThis', '/tmp/doThat']

for cmd in list_cmds:
    Thread(target=exec, args=[cmd]).start()

Upvotes: 0

Jake Levi
Jake Levi

Reputation: 1730

One option is to start a new process for each execute statement using the multiprocessing module (see here for documentation). You create a process using the Process constructor, giving it a target function to perform and any arguments, and tell it to start its function using the start method. If you want to wait for a process to finish, use the join method of that function. Your code might look something like this (make sure your statements are wrapped in an if __name__ == '__main__': block):

import pysftp as sftp
from multiprocessing import Process


if __name__ == '__main__':
    cnopts = sftp.CnOpts()
    cnopts.hostkeys = None
    handle = sftp.Connection(
        '10.0.2.10',
        username='kali',
        password='root',
        cnopts=cnopts
    )
    # Create processes
    p1 = Process(target=handle.execute, args=('/tmp/doThis',))
    p2 = Process(target=handle.execute, args=('/tmp/doThat',))
    # Tell processes to start
    p1.start()
    p2.start()
    # If you want to, then wait for both processes to finish
    p1.join()
    p2.join()

Upvotes: 0

Related Questions