Run local python script on remote machine

33,989

Solution 1

As others have said, pipe it into ssh. But what you will want to do is give the proper arguments. You will want to add -u to get the output back from ssh properly. And want to add - to handle the output and later arguments.

ssh user@host python -u - < script.py

If you want to give command line arguments, add them after the -.

ssh user@host python -u - --opt arg1 arg2 < script.py

Solution 2

Use the remrunner package for python. It copies local scripts to a remote machine and then executes them.

pip install remrunner

python
>> from rumrunner import runner

>> r = runner.Runner(REMOTE_HOST_IPADDR, REMOTE_HOST_USER)
>> rval, stdout, stderr = r.run('/path/to/local/script.py')
>> if rval:
    print stderr
else:
    print stdout
Share:
33,989

Related videos on Youtube

Trismegistos
Author by

Trismegistos

Updated on September 18, 2022

Comments

  • Trismegistos
    Trismegistos almost 2 years

    I wish to run python script that I have locally on disk on remote machine. I used to run bash scripts like this:

    cat script.sh | ssh user@machine
    

    but I do not know how to do same for Python script.

    • jordanm
      jordanm almost 8 years
      cat script.py | ssh user@machine python
    • thrig
      thrig almost 8 years
      Or see ansible for a somewhat more complicated take on the run-code-via-SSH thing.