0

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?

2 Answers2

0

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

Jake Levi
  • 1,329
  • 11
  • 16
0

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()
  • I just don't want to stop waiting, but I don't want that process on my computer. Once I start the process on the remote computer it shouldn't be related to my computer at all. But if I create a process, it will be running in background. – Radhey Patel Sep 25 '20 at 18:07
  • Yes, It'll not! The point is here you created a thread and the control is at your end in managing the created thread (In your RAM) but the process will obviously be running on the remote machine. Hope this is what you're expecting. – Parvathirajan Natarajan Sep 25 '20 at 18:16
  • Thanks for the input, I'll implement that and let you know if it worked. – Radhey Patel Sep 25 '20 at 19:09