Search code examples
linuxshellftpsftpexpect

Expect Script for SFTP not working in bash


I have created a shell script containing an expect script for getting a file from remote location. Everything works well, until some command is sent. Whether it is 'ls' or 'pwd' or any other command, the expect script ends abruptly. Could you guy help me out with this.

NOTE : Security is not a concern, hence not using Public keys.

#!/bin/ksh

FTPREMOTEPATH=/Inbox
FTPREMOTEFILENAME=test.CSV


/usr/bin/expect -f - <<EOFEXPECT1
set timeout 60
spawn sftp -oPort=1002 username@test.server.com
expect {
        default { exit 1}
        -re "failed|invalid password|Permission denied" {exit 2}
        "Connection closed" {exit 1}
        timeout {exit 1}
}

expect "Password:"
send "password\r"

expect {
        default {exit 1}
        -re "password|Enter password for " {puts "Incorrect Password"; exit 2}
        "sftp>" {send "cd $FTPREMOTEPATH \r"}
}

expect "sftp>"
send "pwd\r"

send "get $FTPREMOTEFILENAME \r";

EOFEXPECT1

In above script, the scripts end abruptly after sending cd $FTPREMOTEPATH.

Below is the Output :

$ ./test.sh
spawn sftp -oPort=1002 username@test.server.com
Enter password for username
Password:
sftp> cd /Inbox
sftp> $

Solution

  • Okay, Apparently i was missing expect "sftp>" {send "bye\n"} , before EOF (EOFEXPECT1).

    However, i would still be interested in knowing the significance of bye in expect script.

    Here is the updated and working code :

    #!/bin/ksh
    
    FTPREMOTEPATH=/Inbox
    FTPREMOTEFILENAME=test.CSV
    
    
    /usr/bin/expect -f - <<EOFEXPECT1
    set timeout 60
    spawn sftp -oPort=1002 username@test.server.com
    expect {
            default { exit 1}
            -re "failed|invalid password|Permission denied" {exit 2}
            "Connection closed" {exit 1}
            timeout {exit 1}
    }
    
    expect "Password:"
    send "password\r"
    
    expect {
            default {exit 1}
            -re "password|Enter password for " {puts "Incorrect Password"; exit 2}
            "sftp>" {send "cd $FTPREMOTEPATH \r"}
    }
    
    expect "sftp>"
    send "pwd\r"
    
    send "get $FTPREMOTEFILENAME \r";
    
    expect "sftp>" {send "bye\n"}
    
    EOFEXPECT1