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

shssh

The problem is this: I want to copy files from a remote machine.

I am looking for a way to write a shell script that would connect to the remote machine, get the location of the stored file, once I get the location disconnect from the remote server and use scp from within the local machine with the obtained location to copy the file.

Specifically, I want to know how from a script, I would connect to a remote machine, do tasks on that machine. Disconnect, and continue execution locally.

Best Answer

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).