Shell script from local machine to execute command in remote machine, then continue on the local machine

You can write a script in the following format:

command1
command2
...
ssh user@machine command3
...
command4
command5

You need to setup SSH keys to get command3 executed without prompting you for a password.


Solution 1:

remote_output="$(ssh user@host "remote command")"
scp "user@$host:$remote_output" /local/path

This works by connecting to the remote machine, running some commands, and copying the output to a variable on your local machine. Say, echoing the file path remotely, capturing it locally.

Solution 2:

ssh user@host "determine_path; cat filename" >local_filename

This works by finding and outputting the file directly from remote, and redirecting it to a file locally. This skips scp. This requires that the steps prior to "cat" don't have output (which you can solve with &>/dev/null).


I assume you already have some idea of how you'll identify the file that you want to copy, and that you are able to, or already have, written a script or set of commands that will run on the remote machine that does this identification.

Furthermore I'll also assume that those commands print on standard output the full path to the file, or the relative path to the file, relative to the home directory of the SSH user being used for the copy. In my example, the name of the script is "getfilepath.sh", although it doesn't have to be a shell script, it could be some other executable or even a series of commands.

# Script to be executed on local machine.

# put any leading local commands here.

FILE=$(ssh user@emote getfilepath.sh);
scp user@remotehost:"$FILE" .

# put any trailing local commands here.

In the above code, the "$()" notation is a way of capturing the standard output of a command as a shell variable. It is fairly standard, but if you are using a shell that does not understand it, you can instead surround the command with "back-ticks", which are the accent marks to the left of the 1 key on most US keyboards.

Tags:

Ssh

Sh