在 Linux 命令行中,不能直接在 rsync
或 ssh
命令里明文写密码,因为 SSH 协议本身不支持这种不安全的操作(防止密码泄露)。但如果你不想安装 sshpass
,可以通过以下 3 种替代方案 实现免密码传输:
方法 1:使用 SSH 密钥认证(推荐,最安全)
步骤:
-
在本地生成 SSH 密钥(如果已有
~/.ssh/id_rsa.pub
可跳过):ssh-keygen -t rsa -b 4096
(直接按回车,不设密码)
-
将公钥上传到远程服务器:
ssh-copy-id root@10.80.0.230
需要输入一次密码,之后就不再需要。
-
直接使用
rsync
,无需密码:rsync -avzP --rsh="ssh -o ServerAliveInterval=30" "/root/leon/deepseek/ghcr-io-open-webui-main.tar" root@10.80.0.230:/mnt/ecm-docker-images-tar
✅ 优点:安全、无需额外工具、一劳永逸。
❌ 缺点:需要提前配置 SSH 密钥。
方法 2:使用 expect
脚本(无需 sshpass
)
如果不想用 SSH 密钥,可以用 expect
自动交互输入密码(系统一般自带 expect
,无需安装)。
步骤:
-
创建脚本
rsync_auto.exp
:#!/usr/bin/expect set password "你的密码" set src "/root/leon/deepseek/ghcr-io-open-webui-main.tar" set dest "root@10.80.0.230:/mnt/ecm-docker-images-tar" spawn rsync -avzP --rsh="ssh -o ServerAliveInterval=30" $src $dest expect { "yes/no" { send "yes\r"; exp_continue } "password:" { send "$password\r" } } expect eof
-
赋予执行权限并运行:
chmod +x rsync_auto.exp ./rsync_auto.exp
✅ 优点:无需 sshpass
,密码在脚本中可控。
❌ 缺点:密码仍以明文存储,需注意脚本权限(chmod 700 rsync_auto.exp
)。
方法 3:临时使用 ssh -o StrictHostKeyChecking=no
并手动输入密码(仅免 yes
确认)
如果只是不想手动输入 yes
,但仍可以接受输密码:
rsync -avzP --rsh="ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=30" "/root/leon/deepseek/ghcr-io-open-webui-main.tar" root@10.80.0.230:/mnt/ecm-docker-images-tar
✅ 优点:不用确认 yes
,但仍然需要输密码。
❌ 缺点:无法完全自动化。
总结
方法 | 是否需要密码 | 是否需要额外工具 | 安全性 | 适用场景 |
---|---|---|---|---|
SSH 密钥 | ❌ 无需 | ❌ 无需 | ⭐⭐⭐⭐⭐ | 长期使用 |
expect 脚本 | ✅ 需明文存储 | ❌ 系统自带 | ⭐⭐ | 临时使用 |
StrictHostKeyChecking=no | ✅ 需手动输密码 | ❌ 无需 | ⭐⭐⭐ | 仅免 yes 确认 |
推荐优先使用 SSH 密钥认证,既安全又方便。如果只是临时使用,可以用 expect
脚本。