Is it possible to use Unix commands to cp a file in my subdirectory into a remote computer via SSH?

You may want to use scp for this purpose. It is a secure means to transfer files using the SSH protocol.

For example, to copy a file named yourfile.txt from ~/Downloads to remote computer, use:

scp ~/Downloads/yourfile.txt [email protected]:/some/remote/directory

You can see more examples here.


Though scp is clearly the right tool for this, if for some reason you can't use it you could do something like the following from your local machine to copy, say, a directory structure to the remote machine:

tar -c . | ssh <remote> tar -x

This will tar the current directory on the local machine, and write that tar to stdout which will then be piped to an ssh command where it will execute a remote command to untar the file it reads from stdin

Edited to reflect Dietrich Epp's comment about -f - being the default on both the creation and extraction ends, so not being necessary to specify explicitly.


If you want to do this on more than the rare occasion, I'd suggest mounting the remote filesystem with sshfs if you are using a Unix-like that supports FUSE (Linux, *BSD, Mac OS X). Make a directory under your home directory, say, called ~/remote-server:

    $ mkdir ~/remote-server

Then mount the remote filesystem with sshfs. Replace "yourserver.com" with the host name of your remote machine, and "name of remote directory" with the directory you are using on the remote system.

    $ sudo sshfs [email protected]:/name/of/remote/directory ~/remote-server/

Once this is done, the remote directory is part of your filesystem and you can use all your normal tools on it, including cp:

    $ cp ~/Downloads/your-files ~/remote-server

If you don't already have sshfs installed, you should be able to install it on your computer using your package manager (look for packages named sshfs or fuse-sshfs). For more information, you can read a tutorial online.

This, by the way, is my favorite way of managing files on remote servers. I normally keep one production server and two development servers mounted in this way and use my normal file browsing workflow with them.

Tags:

Ssh

Remote