scp - Linux


Overview

The scp command in Linux is used for secure copy of files and directories between hosts on a network. It leverages SSH for data transfer, providing the same level of security and requiring the same authentication. scp is most effective for transferring files securely over a network and performs tasks similar to the cp command, but over a secured line.

Syntax

The basic syntax of the scp command is:

scp [OPTION] [[user@]SRC_HOST:]file1 [[user@]DEST_HOST:]file2
  • SRC_HOST and DEST_HOST refer to the hostnames or IP addresses of the source and destination machines.
  • user@ specifies the username to connect as on the remote host.
  • file1 and file2 are the source and destination files or directories.
  • Multiple files can be specified to be copied to a destination directory.

Options/Flags

  • -P port: Specifies the port to connect to on the remote host (note it is capital P, not lowercase).
  • -p: Preserves file modification and access times.
  • -r: Recursively copy entire directories.
  • -q: Quiet mode, disables the progress meter as well as warning and diagnostic messages.
  • -C: Enable compression, useful for speeding up transfers.
  • -i identity_file: Use a specified SSH private key for the connection, useful for automated scripts.

Examples

  1. Basic File Copy

    Copy a file from your local machine to a remote server:

    scp localfile.txt user@remotehost:/path/to/destination/
    
  2. Copying Multiple Files

    Copy multiple files to the remote host:

    scp file1.txt file2.txt user@remotehost:/path/to/destination/
    
  3. Directory Copy

    Recursively copy a directory to a remote host:

    scp -r /path/to/localdir user@remotehost:/path/to/destination/
    
  4. Using a Specific SSH Key

    scp -i /path/to/private_key file1.txt user@remotehost:/path/to/destination/
    
  5. Using a Different Port

    scp -P 2222 localfile.txt user@remotehost:/path/to/destination/
    

Common Issues

  • Permission Denied: Ensure you have read permission on the source file and write permission on the destination.
  • No Such File or Directory: Verify the correct paths on both local and remote systems.
  • Connection Refused: Ensure SSH is running on the remote host and the port number is correct.

Integration

Combine scp with other commands to manipulate data before transferring or after receiving it. For instance, to archive a directory and copy it to a remote server:

tar czf - /path/to/dir | scp - user@remotehost:/path/to/destination/dir.tar.gz
  • ssh: Used for running commands on a remote machine.
  • rsync: An alternative to scp that provides more features like incremental file transfer.
  • sftp: A secure file transfer program that uses SSH to securely transfer files between computers.

For more detailed information, you may visit the official OpenSSH scp documentation.