在 Linux 下使用 scp 命令
scp cp ssh
![](/data/attachment/album/201606/13/092323dlqzldtadybppndt.jpg)


scp 是<ruby> 安全拷贝协议 <rp>  （ </rp> <rt>  Secure Copy Protocol </rt> <rp>  ） </rp></ruby>的缩写，和众多 Linux/Unix 使用者所熟知的拷贝（cp）命令一样。scp 的使用方式类似于 cp 命令，cp 命令将一个文件或文件夹从本地操作系统的一个位置（源）拷贝到目标位置（目的），而 scp 用来将文件或文件夹从网络上的一个主机拷贝到另一个主机当中去。


scp 命令的使用方法如下所示，在这个例子中，我将一个叫 “importantfile” 的文件从本机（10.10.16.147）拷贝到远程主机（10.0.0.6）中。在这个命令里，你也可以使用主机名字来替代IP地址。



```
[root@localhost ~]# scp importantfile admin@10.0.0.6:/home/admin/
The authenticity of host '10.0.0.6 (10.0.0.6)' can't be established.
RSA key fingerprint is SHA256:LqBzkeGa6K9BfWWKgcKlQoE0u+gjorX0lPLx5YftX1Y.
RSA key fingerprint is MD5:ed:44:42:59:3e:dd:4c:12:43:4a:89:b1:5d:bd:9e:20.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.6' (RSA) to the list of known hosts.
admin@10.0.0.6's password:
importantfile                                 100%    0     0.0KB/s   00:00
[root@localhost ~]#

```

类似的，如果你想从一个远程主机中取得文件，你可以利用如下的 scp 命令。



```
[root@localhost ~]# scp root@10.10.16.137:/root/importantfile /home/admin/
The authenticity of host '10.10.16.137 (10.10.16.137)' can't be established.
RSA key fingerprint is b0:b0:a3:c3:2e:94:13:0c:29:2e:ba:0b:d3:d6:12:8f.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.10.16.137' (RSA) to the list of known hosts.
root@10.10.16.137's password:
importantfile 100% 0 0.0KB/s 00:00
[root@localhost ~]#

```

你也可以像 cp 命令一样，在 scp 命令中使用不同的选项，scp 的 man 帮助详细地阐述了不同选项的用法和用处。


**示例输出**


![](/data/attachment/album/201606/13/092323sknls0lkaxjrl6ux.jpg)


scp 可选参数如下所示:



```
 -B      采取批量模式（避免询问密码或口令）
 -C      启用压缩。通过指明 -C 参数来开启压缩模式。
 -c 加密方式
         选择在传输过程中用来加密的加密方式 这个选项会被直接传递到 ssh(1)。
 -F ssh 配置
         给 ssh 指定一个用来替代默认配置的配置文件。这个选项会被直接传递到 ssh(1)。
 -l 限速
         限制命令使用的带宽，默认单位是 Kbit/s。
 -P 端口
         指定需要的连接的远程主机的端口。  
         注意，这个选项使用的是一个大写的“P”，因为小写的“-p”已经用来保留目标文件的时间和模式相关信息。（LCTT 译注：ssh 命令中使用小写的“-p”来指定目标端口。）
 -p      保留文件原来的修改时间，访问时间以及权限模式。
 -q      静默模式：不显示来自 ssh(1) 命令的进度信息，警告和诊断信息。
 -r      递归拷贝整个目录。
         注意，scp 命令在树形遍历的时候同样会跟随符号连接，复制所连接的文件。
 -v      详细模式。scp 和 ssh(1) 将会打印出处理过程中的调试信息。这可以帮助你调试连接、认证和配置方面的问题。

```

**详细模式**


利用 scp 命令的 -v 选项，你可以得到认证、调试等的相关细节信息。


![](/data/attachment/album/201606/13/092324qznxlxgclpcfpn74.jpg)


当我们使用 -v 选项的时候，一个简单的输出如下所示：



```
[root@localhost ~]# scp -v abc.txt admin@10.0.0.6:/home/admin
Executing: program /usr/bin/ssh host 10.0.0.6, user admin, 
command scp -v -t/home/admin
OpenSSH_7.1p1, OpenSSL 1.0.2d-fips 9 Jul 2015
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 56: Applying options for *
debug1: Connecting to 10.0.0.6 [10.0.0.6] port 22.
debug1: Connection established.
debug1: Server host key: ssh-rsa SHA256:LqBzkeGa6K9BfWWKgcKlQoE0u+gjorX0lPLx5YftX1Y
debug1: Next authentication method: publickey
debug1: Trying private key: /root/.ssh/id_rsa
debug1: Trying private key: /root/.ssh/id_dsa
debug1: Trying private key: /root/.ssh/id_ecdsa
debug1: Trying private key: /root/.ssh/id_ed25519
debug1: Next authentication method: password
admin@10.0.0.6's password:
debug1: Authentication succeeded (password).
Authenticated to 10.0.0.6 ([10.0.0.6]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending command: scp -v -t /home/admin
Sending file modes: C0644 174 abc.txt
Sink: C0644 174 abc.txt
abc.txt                                                                                                                               100%  174     0.2KB/s   00:00
Transferred: sent 3024, received 2584 bytes, in 0.3 seconds
Bytes per second: sent 9863.3, received 8428.1
debug1: Exit status 0
[root@localhost ~]#

```

当我们需要拷贝一个目录或者文件夹的时候，我们可以使用 -r 选项，它会递归拷贝整个目录。


![](/data/attachment/album/201606/13/092325wpclwopqcxtia5ug.jpg)


**静默模式**


如果你想要关闭进度信息以及警告和诊断信息，你可以通过使用scp命令中的-q选项.


![](/data/attachment/album/201606/13/092331cjsts7txmrtzrhrr.jpg)


上一次我们仅仅使用 -r 参数，它显示了逐个文件的信息，但这一次当我们使用了 -q 参数，它就不显示进度信息。


利用 scp 的 -p 选项来保留目标文件的更新时间，访问时间和权限模式。


![](/data/attachment/album/201606/13/092332b555xa5wd5kpp5zy.jpg)


**通过 -P 选项来指定远程主机的连接端口**


scp 使用 ssh 命令来在两个主机之间传输文件，因为 ssh 默认使用的是22端口号，所以 scp 也使用相同的22端口号。


如果我们希望改变这个端口号，我们可以使用 -P（大写的 P，因为小写的 p 用来保持文件的访问时间等）选项来指定所需的端口号。


举个例子，如果我们想要使用2222端口号，我们可以使用如下的命令



```
[root@localhost ~]# scp -P 2222 abcd1 root@10.10.16.137:/root/

```

**限制命令使用的带宽，指定的单位是 Kbit/s**


如下所示，我们可以使用 -l 参数来指定 scp 命令所使用的带宽，在此我们将速度限制为512kbit/s。


![](/data/attachment/album/201606/13/092333ru55gixi5dux51o5.jpg)


**开启压缩**


如下所示，我们可以通过开启 scp 命令的压缩模式来节省传输过程中的带宽和时间。


![](/data/attachment/album/201606/13/092337zk2skizc14wqonnn.jpg)


**选择加密数据的加密方式**


scp 默认使用 AES-128 的加密方式，如果我们想要改变这个加密方式，可以通过 -c(小写的 c) 参数来指定其他的加密方式。


![](/data/attachment/album/201606/13/092337q0wuszynb2spv20a.jpg)


现在你可以利用 scp（Secure copy）命令在你所属网络中的两个节点之间安全地拷贝文件了。




---


via: <https://www.unixmen.com/scp-command-linuxunix/>


作者：[Naga Ramesh](https://www.unixmen.com/author/naga/) 译者：[lujianbo](https://github.com/lujianbo) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
**scp** means **Secure Copy Protocol**, and almost every Linux/Unix user knows how the cp command works.** scp** also works like** cp** command, cp command copies files or folders from one location i.e source to other location i.e target in local system, but scp copies the files from one host to another host in network.

The Secure Copy Protocol is essentially a network protocol that users can use if they want to securely copy files or folders between Linux or Unix systems on the same network. The scp command-line utility is known to be much safer than the cp utility.

The SCP command protects the data that you copy across systems using an SSH (Secure Shell) connection. SSH encrypts the files and passwords that are being transmitted, and therefore, even if another party intercepts the traffic, the information is unreadable since it is encrypted.

The SCP command is most commonly used when transferring sensitive information between systems.

**Syntax of the SCP Command**

Before learning to use the command, you must review the syntax. The command takes the following form:

scp [OPTION] [user@] SRC_HOST:lfile1 [user@]DEST_HOST:]file2

In the syntax:

- OPTION refers to the scp options, such as the limit, the cipher used, the SSH configuration, recursive copy and others
- [user@]SRC_HOST:lfile1 refers to the source file
- [user@]DEST_HOST:]file2 refers to the destination file

If you specify local files, you must use the absolute or relative path. On the other hand, when specifying remote files, you must include both user and host details.

The scp command has several options that you can use to control its behavior. The most commonly used options include:

**-c**: It forces the command to compress the data when sending to the destination**-r**: It instructs the command to copy the directories recursively**-q**: It suppresses the progress meter and also the non-error messages**-p**: It preserves the transferred file’s modification and access times**-P**: It specifies the remote host’s SSH port

We specify the full list of useable options for the scp command later in this post.

**What You Need to Know Before Using the SCP Command**

As mentioned earlier, the scp command relies on ssh to transfer data between machines. For this reason, it requires an SSH key to authenticate the transfer on remote systems.

The command uses the colon (:) to differentiate between the local and remote locations.

It’s important to note that to copy a file, you will at minimum require read permissions to the source file. Further, you will need write permission on the target system.

If you copy files with the same name and location on both systems, you must remember that the scp command will overwrite the files without alerting you.

Lastly, when using the command to transfer large files, it’s considered best practice to run the command inside a tmux session or a screen to avoid potential failure.

**How to Use the SCP Command**

The usage of the scp command is as follows, here i copy a file named importantfile from **local system**(10.10.16.147) to **Remote system**(10.0.0.6) here instead of ip address you can also use System name.

[root@localhost ~]# scp importantfile admin@10.0.0.6:/home/admin/ The authenticity of host '10.0.0.6 (10.0.0.6)' can't be established. RSA key fingerprint is SHA256:LqBzkeGa6K9BfWWKgcKlQoE0u+gjorX0lPLx5YftX1Y. RSA key fingerprint is MD5:ed:44:42:59:3e:dd:4c:12:43:4a:89:b1:5d:bd:9e:20. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '10.0.0.6' (RSA) to the list of known hosts. admin@10.0.0.6's password: importantfile 100% 0 0.0KB/s 00:00 [root@localhost ~]#

Similarly if you want to get a file from remote system you can use scp command as follows

[root@localhost ~]# scp root@10.10.16.137:/root/importantfile /home/admin/ The authenticity of host '10.10.16.137 (10.10.16.137)' can't be established. RSA key fingerprint is b0:b0:a3:c3:2e:94:13:0c:29:2e:ba:0b:d3:d6:12:8f. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '10.10.16.137' (RSA) to the list of known hosts. root@10.10.16.137's password: importantfile 100% 0 0.0KB/s 00:00 [root@localhost ~]#

You can also use various options along with** scp** command like **cp** command,The man page of the scp command clearly explain about the usage of various options and advantages of that.

**Sample Output.**


The options are as follows: -B Selects batch mode (prevents asking for passwords or passphrases). -C Compression enable. Passes the -C to enable compression. -c cipher Selects the cipher to use for encrypting the data transfer. This option is directly passed to ssh(1). -F ssh_config Specifies an alternative per-user configuration file for ssh. This option is directly passed to ssh(1). -l limit Limits the used bandwidth, specified in Kbit/s. -P port Specifies the port to connect to on the remote host. Note that this option is written with a capital ‘P’, because -p is already reserved for preserving the times and modes of the file. -p Preserves modification times, access times, and modes from the original file. -q Quiet mode: disables the progress meter as well as warning and diagnostic messages from ssh(1). -r Recursively copy entire directories. Note that scp follows sym‐ bolic links encountered in the tree traversal. -v Verbose mode. Causes scp and ssh(1) to print debugging messages about their progress. This is helpful in debugging connection, authentication, and configuration problems.

The scp command along with **-v** option you can get detailed information about authentication, debugging information etc.

Sample output is like when we pass the option **-v**

[root@localhost ~]# scp -v abc.txt admin@10.0.0.6:/home/admin Executing: program /usr/bin/ssh host 10.0.0.6, user admin, command scp -v -t/home/admin OpenSSH_7.1p1, OpenSSL 1.0.2d-fips 9 Jul 2015 debug1: Reading configuration data /etc/ssh/ssh_config debug1: /etc/ssh/ssh_config line 56: Applying options for * debug1: Connecting to 10.0.0.6 [10.0.0.6] port 22. debug1: Connection established. debug1: Server host key: ssh-rsa SHA256:LqBzkeGa6K9BfWWKgcKlQoE0u+gjorX0lPLx5YftX1Y debug1: Next authentication method: publickey debug1: Trying private key: /root/.ssh/id_rsa debug1: Trying private key: /root/.ssh/id_dsa debug1: Trying private key: /root/.ssh/id_ecdsa debug1: Trying private key: /root/.ssh/id_ed25519 debug1: Next authentication method: password admin@10.0.0.6's password: debug1: Authentication succeeded (password). Authenticated to 10.0.0.6 ([10.0.0.6]:22). debug1: channel 0: new [client-session] debug1: Requesting no-more-sessions@openssh.com debug1: Entering interactive session. debug1: Sending environment. debug1: Sending command: scp -v -t /home/admin Sending file modes: C0644 174 abc.txt Sink: C0644 174 abc.txt abc.txt 100% 174 0.2KB/s 00:00 Transferred: sent 3024, received 2584 bytes, in 0.3 seconds Bytes per second: sent 9863.3, received 8428.1 debug1: Exit status 0 [root@localhost ~]#

If we need to copy the Directories or folders we can use the option –**r**. It Recursively copy entire directories

**Quiet mode:**

If you want disables the progress meter as well as warning and diagnostic messages pass the argument **-q** along with **scp** command.

last time we pass the argument **-r** only then it shows the information file by file, but when we pass the argument **-q** it disables the progress meter this time.

Preserves modification times, access times, and modes from the original file by passing the option **-p** along with scp.


** Specifies the port to connect to on the remote host by using the option -P.**

**scp** uses the **ssh** to transfer the files between hosts, ssh uses the **port number 22** so the scp also uses the same port number 22.

If we want to change the port number we can pass the particular port number along with -P(capital P because small p uses for preserving access time etc.)

for example if we want to use port number 2222 then the command is as follows

[root@localhost ~]# scp -P 2222 abcd1 root@10.10.16.137:/root/

**Limits the used bandwidth, specified in Kbit/s**

we can limit the bandwidth by using the argument **-l** option as follows. here i used the limit is 512kbit/s


**Compression enable**

we can enable the compression mode when we transfer the data through scp command to save tha bandwidth and time as follows


**Selects the cipher to use for encrypting the data**

By default scp uses AES-128, if we want to change the encryption then we can pass the argument -c(small c) along with scp.

Now you can transfer the files between different nodes in your network securely by using scp(Secure copy).

**Conclusion**

The scp command is recognized as an excellent alternative to FTP since it is inherently insecure. Since the command uses the regular command line and SSH, it provides a seamless command set for managing files.

If you intend to repeatedly transfer files between the same systems, consider simplifying your workflow by specifying all of the connections in the SSH config file.