scp 命令在 bash 脚本中无法正常工作

scp command not working inside expect in bash script

while [ $FileLine -le $FileListLines ];
                do
                        # extract each line from FileList
                        str=$(tail -n+$FileLine ../$FileList | head -n1)
                        hostpath=$username@$ip:$str
                        export hostpath ip
                        expect -c '
                                spawn bash -c "scp -pr $env(hostpath) $env(ip)"
                                expect {
                                        "(yes/no)?"{
                                                send "yes\r"
                                                expect "*?assword:*"
                                                send "password\r"
                                                }
                                        "*?assword:*"{
                                                send "password\r"
                                                }
                                        }
                                '
                        FileLine=$(( $FileLine + 1 ))
                done

以上是 bash 脚本的一部分。 expect 块中的 scp 命令不起作用,也就是说,远程计算机中的文件没有被复制到本地计算机。

pathhostname 相同的 scp 命令在从终端 运行 时工作正常。

在预期代码的末尾添加 expect eof 否则 scp 进程将在密码发送后立即终止。 (还在 expect {} 块中的 模式 { 之间添加一个 space,但不确定这是否是一个问题。)

expect -c '
    spawn bash -c "scp -pr $env(hostpath) $env(ip)"
    expect {
        "(yes/no)?" {
            send "yes\r"
            expect "*?assword:*"
            send "password\r"
        }
        "*?assword:*" {
            send "password\r"
        }
    }
    expect eof
'

更新

刚试过 "(yes/no)?"{ 不行。 模式 { 之间的 space 是必需的,因此它应该是 "(yes/no)?" {.