Secure Copy
The scp (Secure Copy) command is used to securely transfer files between a local host and a remote host, or between two remote hosts, over SSH. Here’s a quick guide to get you started with scp:
Basic Syntax
scp [options] <source> <destination>
<source>: The file or directory you want to copy.
<destination>: The location where you want to copy the file or directory.
Common Use Cases
Copy a file from local machine to remote server:
Write permission is needed.
scp /path/to/local/file user@remote:/path/to/remote/directory
Example:
scp /home/user/file.txt user@remote:/home/user/destination/
This copies file.txt from your local machine to the remote machine at /home/user/destination/.
Copy a file from remote server to local machine:
Read permission is needed.
scp user@remote:/path/to/remote/file /path/to/local/directory
Example:
scp user@remote:/home/user/file.txt /home/localuser/destination/
This copies file.txt from the remote server to your local machine.
Copy a directory recursively (use the -r option):
scp -r /path/to/local/directory user@remote:/path/to/remote/directory
Example:
scp -r /home/user/folder user@remote:/home/user/destination/
This copies the entire folder from your local machine to the remote server.
Copy a file from one remote server to another remote server:
scp user1@remote1:/path/to/file user2@remote2:/path/to/destination
Example:
scp user1@remote1:/home/user1/file.txt user2@remote2:/home/user2/destination/
This copies a file from remote1 to remote2.
Useful Options:
-r: Copy directories recursively.
-P <port>: Specify a non-default SSH port (if the remote server uses a custom port).
scp -P 2222 file.txt user@remote:/path/to/destination/
-i <identity_file>: Use a specific private key file for SSH authentication.
Need to create the key and add public key to server.
ssh-keygen -t ed25519 -C "my_key" -f /path/to/private_key
ssh-copy-id -i /path/to/private_key.pub user@remote
scp -i /path/to/private_key file.txt user@remote:/path/to/destination/
Example Scenarios:
Copy file from local to remote:
scp myfile.txt user@192.168.1.10:/home/user/
Copy directory from local to remote:
scp -r mydir/ user@192.168.1.10:/home/user/
Copy file from remote to local:
scp user@192.168.1.10:/home/user/myfile.txt /home/localuser/
Copy between two remote servers:
scp user@remote1:/path/to/file.txt user@remote2:/path/to/destination/