如何在Linux中使用SCP命令进行文件传输?

SCP(Secure Copy)是用于在Linux主机之间进行安全文件传输的命令。它使用SSH协议,可以在传输过程中对数据进行加密。
SCP的基本语法为:

scp [选项] 源地址 目标地址
常用选项有:
- -P :指定端口号,默认为22
- -r :递归复制目录
- -v :详细输出模式
- -C :启用压缩

示例:

  1. 从本地复制文件到远程主机:
# 复制文件
scp /path/to/file.txt username@host:/path/to/dest  

# 复制目录
scp -r /path/to/dir username@host:/path/to/dest
  1. 从远程主机复制文件到本地:
scp username@host:/path/to/file.txt /path/to/dest

scp -r username@host:/path/to/dir /path/to/dest  
  1. 在两台远程主机之间复制文件:
scp username@host1:/path/to/file.txt username@host2:/path/to/dest
  1. 通过SSH跳板登录进行文件复制:
scp -J user@intermediary_host:22 file.txt user@target_host:file.txt
  1. 通过SSH隧道进行文件复制:
# 在本地主机监听9000端口
ssh -L 9000:localhost:22 user@intermediary_host  

# 通过本地9000端口复制文件到target_host
scp -P 9000 file.txt user@localhost:file.txt