Execute Python scripts over SSH without copying them

Posted on 2025-01-05 in Trucs et astuces

You can run scripts (written in Python or any other language) directly on a server if the proper interpreter is installed. I recently used it to run a Python script over several servers without the need to copy the relevant script on the server. It all relies on the following bash operators:

  • < to send the content of a file to a command.
  • <<< to send text to a command.
  • <<EOT and EOT to send code between these tow markers to a command.

With this knowledge, I built the first script to loop over the servers and send the script to execute on it:

#!/usr/bin/env bash

servers=(server1 server2)

for server in "${servers[@]}"; do
    echo "Connecting to $server"
    # Thanks to < SSH will execute the commands contained in the script.
    ssh $server < ./script-to-run-on-server.sh
done

And the script to run on the server, saved in script-to-run-on-server.sh in the same folder as the one ones (adapt names and path to match what you are doing):

#!/usr/bin/env bash

# Send a single command.
python <<< "import sys; print(sys.version)"

for dir in apps/*; do
    echo "Executing in $dir"
    # You program must be between this line and EOT
    python <<EOT
# Python code must not be indented!
import os
print(os.getcwd())
# Must NOT be indented or the end of the command text won’t be caught.
EOT

done

And that’s all it takes!