You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Expect在SCP中传递多密码实现远程文件传输失败求助

解决方案

1. 处理首次连接的主机密钥确认

首次连接远程主机时,scp会弹出主机密钥确认提示(如Are you sure you want to continue connecting (yes/no)?),这会导致expect匹配不到密码提示而卡住。修改脚本加入该场景的处理:

#!/usr/bin/expect

set timeout -1

spawn scp -3 scp://remote_source_user@host1:port1/home/source/test.txt scp://remote_target_user@host2:port2/home/target/

# 处理源主机的密钥确认和密码提示
expect {
    "Are you sure you want to continue connecting (yes/no)?" {
        send "yes\r"
        exp_continue
    }
    "remote_source_user@host1's password:" {
        send "SOURCE_PASSWORD\r"
    }
}

# 处理目标主机的密钥确认和密码提示
expect {
    "Are you sure you want to continue connecting (yes/no)?" {
        send "yes\r"
        exp_continue
    }
    "remote_target_user@host2's password:" {
        send "TARGET_PASSWORD\r"
    }
}

expect eof

2. 使用通用匹配模式提升兼容性

避免硬编码完整的提示文本,改用模糊匹配,同时支持动态变量配置:

#!/usr/bin/expect

set timeout -1
set src_user "remote_source_user"
set src_pass "SOURCE_PASSWORD"
set dst_user "remote_target_user"
set dst_pass "TARGET_PASSWORD"
set src_host "host1"
set src_port "port1"
set dst_host "host2"
set dst_port "port2"

spawn scp -3 scp://$src_user@$src_host:$src_port/home/source/test.txt scp://$dst_user@$dst_host:$dst_port/home/target/

expect {
    "*$src_user@*'s password:" {
        send "$src_pass\r"
        exp_continue
    }
    "*$dst_user@*'s password:" {
        send "$dst_pass\r"
        exp_continue
    }
    "Are you sure you want to continue connecting (yes/no)?" {
        send "yes\r"
        exp_continue
    }
    eof
}

3. 开启调试模式定位问题

在脚本开头添加exp_internal 1开启调试输出,可查看expect实际接收到的所有交互内容,快速定位匹配失败的原因:

#!/usr/bin/expect
exp_internal 1  # 开启调试输出,会打印所有交互细节
set timeout -1

# 后续脚本内容不变

内容的提问来源于stack exchange,提问作者user275616

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 11:15:59