# scp 命令

scp(Secure Copy)命令用于在网络上进行安全的文件传输。

# 语法

scp [选项] [[用户名@]主机1:]文件1 [[用户名@]主机2:]文件2

# 常用选项

  • -P port: 指定端口号(默认22)
  • -r: 递归复制目录
  • -p: 保留原文件的修改时间和权限
  • -q: 静默模式,不显示进度信息
  • -C: 启用压缩

# 使用示例

# 从本地复制文件到远程服务器
scp file.txt user@remote:/path/to/destination/

# 从远程服务器复制文件到本地
scp user@remote:/path/to/file.txt /local/path/

# 复制目录
scp -r local_directory user@remote:/path/to/destination/

# 指定端口
scp -P 2222 file.txt user@remote:/path/to/destination/

# 在两个远程主机之间复制
scp user1@host1:/file.txt user2@host2:/path/

# 使用场景

  1. 文件上传下载
  2. 服务器间文件传输
  3. 备份文件
  4. 代码部署

# 性能优化

  1. 使用压缩选项 -C

    scp -C large_file.tar user@remote:/path/
    
  2. 对于大量小文件,先打包再传输

    tar czf - directory | ssh user@remote 'tar xzf - -C /path/'
    

# 注意事项

  1. 文件权限

    • 确保有足够的读写权限
    • 使用 -p 选项保留原文件属性
  2. 网络带宽

    • 大文件传输时注意网络负载
    • 考虑使用压缩选项
  3. 安全性

    • 使用SSH密钥认证
    • 避免在命令行中明文输入密码