简体   繁体   中英

I'm not able to connect sftp using expect script

I'm not able to identify where I'm doing wrong.Please let me know if I'm doing wrong.

#!/usr/bin/bash

File_Sftp ()
{
    set user="xxxx"
    set password="xxxxx"
    set host="ftp.xxxx.xxxx.com"

    STATUS=$(
    expect << EOF
    spawn sftp $user@$host
    expect "User Name:"
    send "$user\r"
    expect "Password:"
    send "$password\r"
    expect "sftp> "
    send "cd in\r"
    expect "sftp> "
    send "get $1\r"
    expect "sftp> "
    send "exit\r"
EOF
    )

    if [ "$(echo $STATUS | grep -c 226)" -ge 1 ]; then
      echo "Success";
    else
      echo "Unsuccessful" ;
    fi
}

File_Sftp "/usr/local/bin/xxxxxx.txt"

Whenever I'm trying to execute above shell script I got below error:

send: spawn id exp4 not open
    while executing
"send "\r""
Unsuccessful

These bash lines don't do what you think:

set user="xxxx"
set password="xxxxx"
set host="ftp.xxxx.xxxx.com"

They are not setting variable values, they are setting the positional parameter $1 to the given string. The actual variables are still unset .

spawn would have failed trying to launch sftp $user@$host (actually sftp @ with the unset variables), the expect "User Name:" would have timed out after the default 10 seconds, and then the error message comes from send "$user\\r" (or send "\\r" with the unset variables) -- no spawned process to interact with.

You can see this if you use expect -d <<EOF while testing (turning on expect's verbose debugging output)

You want

user="xxxx"
password="xxxxx"
host="ftp.xxxx.xxxx.com"

or, since this is bash, and we want to promote good programming practices (no global variables)

local user="xxxx"
local password="xxxxx"
local host="ftp.xxxx.xxxx.com"

Add an expect eof after sending "exit"


To see if 226 appears in expect's output, I would change this

if [ "$(echo $STATUS | grep -c 226)" -ge 1 ]; then

to

if grep -q '\<226\>' <<< "$STATUS" ; then

or

if [[ $STATUS == *226* ]]; then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM