The problem with executing commands via SSH is that, in general, you need to write them yourself or upload a script file. Despite this, with a little bash knowledge, you can pass entire scripts via SSH without having the .sh
file on remote machine.
The answer: pass script over standard input
The SSH command has a mode where you can run any command on a remote server. To run multiple commands, you will need to use the following trick:
ssh user@remotehost 'bash -s' < script.sh
the bash -s
command means “run the following commands in a new bash session”. the -s
The flag makes it read from standard input, and the < script.sh
bit will read a local script file to standard input.
The file is fully read locally and everything is sent to the remote server without uploading anything. This requires you to put all the commands in a separate script file.
Running many remote commands within one script
And, instead, you want to run a part of a shell script on another server, but not all, you can include nested blocks like the following in your script:
ssh user@remotehost 'bash -s' <<'ENDSSH' # The following commands run on the remote host echo "test" cd /home/ pwd ENDSSH
This works because bash -s
expect any type of standard input. the <<'ENDSSH'
The policy creates a structure “here-document”, simply passing all the characters between it and the termination “ENDSSH” to the standard entrance and, because, to the remote host via SSH.
doing it this way means that you can keep everything in one script file, instead of creating a new one to run on the remote.