0

I'm trying to write a Python program that executes a local Python script on a remote host and lets me communicate with the script when it's running.

My code currently consists of the two files run.py and remote.py:

run.py:

import os
import subprocess as sp

with open(os.path.join(os.path.dirname(__file__), "remote.py")) as scriptf:
    node_script = scriptf.read()

sess = sp.Popen(["ssh", "remote_host", "/usr/bin/python -"], stdin=sp.PIPE, stdout=sp.PIPE)
stdout, stderr = sess.communicate(node_script)
print(stdout, stderr)
sess.stdin.write("Print me this!\n")

remote.py:

import sys

print("Hello!")

while True:
    line = input()
    print(line)

This gives me the following error:

$ python run.py
Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
EOFError: EOF when reading a line
('Hello!\n', None)
Traceback (most recent call last):
  File "run.py", line 10, in <module>
    sess.stdin.write("Print me this!\n")
ValueError: I/O operation on closed file

Is there any way I can pipe a python script into a remote Python interpreter like this AND be able to use something like input() on that script later? How could I change my example to work?

janoliver
  • 7,744
  • 14
  • 60
  • 103
  • this is basically the use-case of a REST API. If you want to ssh into the remote host and run commands on it I would recommend [pexpect](https://pexpect.readthedocs.io/en/stable/api/pexpect.html#run-function) or maybe you want to look into Ansible? – monkut Sep 18 '19 at 08:01
  • There is a similar thing on github to do this . https://github.com/syedjafer/Serial-Activity/blob/master/kill.py – Syed Jafer Sep 18 '19 at 08:04
  • @syedjafer: `kill.py` seems to copy files first, which I don't want to. @monkut: I'm not looking for an ansible or pexpect solution. I'm aware that there are other ways to run commands on a remote server. – janoliver Sep 18 '19 at 08:06

1 Answers1

0

You can try using paramiko-sftp link to transfer python script to remote system and login to remote system using paramiko-ssh link to run the script on remote system.

sushanth
  • 8,275
  • 3
  • 17
  • 28
  • Of course I could transfer the script beforehand, but I'd rather not create any files on the remote host for some reasons. Thank you for the suggestion, though. (Also, I need a solution requiring nothing but a stock python installation, without additional packages). – janoliver Sep 18 '19 at 08:03