不能直接在 rsync 或 ssh 命令里明文写密码

在 Linux 命令行中,不能直接在 rsyncssh 命令里明文写密码,因为 SSH 协议本身不支持这种不安全的操作(防止密码泄露)。但如果你不想安装 sshpass,可以通过以下 3 种替代方案 实现免密码传输:


方法 1:使用 SSH 密钥认证(推荐,最安全)

步骤:

  1. 在本地生成 SSH 密钥(如果已有 ~/.ssh/id_rsa.pub 可跳过)

    ssh-keygen -t rsa -b 4096
    

    (直接按回车,不设密码)

  2. 将公钥上传到远程服务器

    ssh-copy-id root@10.80.0.230
    

    需要输入一次密码,之后就不再需要。

  3. 直接使用 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,无需安装)。

步骤:

  1. 创建脚本 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
    
  2. 赋予执行权限并运行

    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 脚本。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值