Video Lesson: Copy files remotely with scp over SSH

Copy files remotely with scp over SSH

Learn how to securely copy files and directories between local and remote systems over SSH.


Lesson Content

The scp command is similar to cp, but it copies files to and from a remote host over SSH.

Start by creating a file named bar.txt:

echo "foo" > bar.txt

To copy bar.txt to a remote host, specify the local file first, followed by the remote connection string and a colon. The path after the colon is the destination on the remote host. This example copies the file to the remote user’s home directory:

scp bar.txt username@remotehost:

The remote connection string uses the format username@remotehost. By default, scp connects using your default SSH key and port 22.

To use a different SSH private key, add the -i option followed by the key path:

scp -i ~/.ssh/other_key bar.txt username@remotehost:

If the SSH server listens on a port other than 22, add the uppercase -P option followed by the port number:

scp -P 2022 bar.txt username@remotehost:

You can combine the identity and port options when both are needed:

scp -i ~/.ssh/other_key -P 2022 bar.txt username@remotehost:

Use the -r option to copy an entire folder recursively. Create a foo folder and add a bar.txt file to it:

mkdir foo
echo baz > foo/bar.txt

Then copy the complete folder to the remote user’s home directory:

scp -r foo username@remotehost:

To copy a file from the remote host to your local machine, reverse the order of the source and destination. Put the remote connection string first, followed by a colon and the remote file path. The second parameter is the local destination. ./ represents the current directory:

scp username@remotehost:bar.txt ./

You can also give the copied file a new local name by including that name in the destination path:

scp username@remotehost:bar.txt ./local-bar.txt

Copying a folder back works the same way, with the -r option:

scp -r username@remotehost:foo ./

The same SSH options apply when copying from the remote host:

scp -i ~/.ssh/other_key -P 2022 -r username@remotehost:foo ./
Maggie

Hey, I'm Maggie! 👋

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Notes

Keep track of what you learn!