scp(secure copy)命令可以在本地主机和远程主机之间,或者两个远程主机之间安全地复制文件和目录。它使用SSH协议进行数据传输,提供加密的传输通道。
scp [选项] 源文件 目标文件
| 选项 | 说明 |
|---|---|
| -r | 递归复制整个目录 |
| -P port | 指定远程主机的端口号 |
| -p | 保留原文件的修改时间、访问时间和权限 |
| -v | 详细模式,显示详细的传输过程 |
| -C | 启用压缩传输 |
| -i identity_file | 指定身份文件(私钥) |
| -l limit | 限制带宽使用(单位:Kbit/s) |
将本地文件复制到远程主机的指定目录:
# 复制文件到远程主机
scp localfile.txt username@remotehost:/path/to/destination/
# 使用特定端口
scp -P 2222 localfile.txt username@remotehost:/home/username/
# 保留文件属性
scp -p localfile.txt username@remotehost:/tmp/
从远程主机下载文件到本地:
# 从远程主机复制文件
scp username@remotehost:/path/to/remote/file.txt /local/path/
# 使用密钥文件认证
scp -i ~/.ssh/id_rsa username@remotehost:/path/to/file.txt ./
# 显示详细传输信息
scp -v username@remotehost:/path/to/file.txt ./
递归复制整个目录及其内容:
# 复制本地目录到远程
scp -r /local/directory username@remotehost:/remote/path/
# 从远程复制目录到本地
scp -r username@remotehost:/remote/directory /local/path/
通过本地主机在两个远程主机之间传输文件:
# 从host1复制到host2
scp user1@host1:/path/to/file user2@host2:/path/to/destination
对大文件启用压缩以提高传输速度:
# 启用压缩传输大文件
scp -C largefile.iso username@remotehost:/backup/
限制scp使用的带宽,避免影响其他网络服务:
# 限制带宽为1000 Kbit/s
scp -l 1000 bigfile.tar.gz username@remotehost:/downloads/
| 场景 | 格式 | 示例 |
|---|---|---|
| 本地文件 | 绝对或相对路径 | /home/user/file.txt 或 ./file.txt |
| 远程文件 | username@hostname:path | user@example.com:/home/user/file.txt |
| 使用特定端口 | username@hostname:port:path | user@example.com:2222:/path/file |
检查SSH服务是否运行,端口是否正确:
# 检查SSH服务状态
systemctl status sshd
# 检查防火墙设置
firewall-cmd --list-all
检查文件权限和目录权限:
# 检查文件权限
ls -l filename
# 检查目录权限
ls -ld directoryname
# 确保有写入权限