Supratim Das Supratim Das - 6 months ago 72
Bash Question

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


The above is a part of a bash script. The
scp
command in the
expect
block is not working, that is, files from the remote machine are not getting copied to the local machine.

The same
scp
command with the
path
and
hostname
is working fine when being run from the terminal.

Answer

Add expect eof at the end of the expect code otherwise the scp process would be killed right after the password is sent. (Also add a space between the pattern and { in the expect {} block though not sure if that's a problem.)

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
'

UPDATE

Just tried and "(yes/no)?"{ would not work. The space between the pattern and { is required so it should be "(yes/no)?" {.