Search code examples
python-2.7sshtcpsubprocessopenssh

How to get a python program executed remotely (which will communicate live with the host machine for next few minutes) via ssh connection?


I need a TCP connection (client-server model). I put my server program on remote machine using "sftp". Now I need this server program to be executed (listening...) on remote machine after which I can run the client program on my machine to establish the connection. Please suggest a method to get the server executed remotely via ssh connection. I have tried ssh.exec_command("sudo python server.py",shell = True) and writing this command to a bash script and running that bash script but the program runs for a while(milliseconds) and then as soon as the parent code moves to the line next to "ssh.exec_command(...)" (or you can say as soon as it executes the line ssh_client.close()) the terminal running server gets closed. Hence, upon running the client.py "Connection refused error" is returned. I have also tried many other things like running the program in background using 'nohup' etc. Please don't suggest me to use ssh for all the tasks.


Solution

  • As of now, I am still unable to find a legit way to do the task but I guessed a hack which worked for me and will definitely work for anyone. So, in the parent program, it is something like

    client = SSHClient()
    client.load_system_host_keys()
    client.connect('ssh.example.com')
    stdin, stdout, stderr = client.exec_command('python server_program.py')
    client.close() 
    

    But above code fails to keep running the server_program.py because as soon as the line client.close() is executed the parent program ends and so does the child program.

    But the hack is to put above code in a new python program say new.py and add a line time.sleep(A LARGE RANDOM NUMBER) before client.close() and run this 'new.py' from parent program using

    process = subprocess.Popen(['python new.py'], stdout=PIPE, stderr=PIPE, shell=True)
    

    hence the parent will keep running and so will do the child. Finally, when you have done your work, you may kill the program using process.kill().