3

Since I have issues with my remote server [authorized_keys...] I wrote a script on my local machine that uses expect command to ssh into the server and then perform cd and then git pull

But I can't get this thing to work:

#!/usr/bin/expect
spawn ssh USER@IP_ADDRESS   
expect {
    "USER@IP_ADDRESS's password:"  {
        send "PASSWORD\r"
    }
    "[USER@server ~]$" {
        send "cd public_html"
    }
}   
interact

Do I need to escape some chars? even when I try it still ignores the cd command.

1 Answer 1

5

[ is special to TCL so will need proper handling, either via "\[quotes]" or by replacing the quotes with curly braces {[quotes]}. A more complete example would look something like

#!/usr/bin/env expect

set prompt {\[USER@HOST[[:blank:]]+[^\]]+\]\$ }
spawn ssh USER@HOST

expect_before {
    # TODO possibly with logging, or via `log_file` (see expect(1))
    timeout { exit 1 }
    eof { exit 1 }
}

# connect
expect {
    # if get a prompt then public key auth probably logged us in
    # so drop out of this block
    -re $prompt {}
    -ex "password:" {
        send -- "Hunter2\r"
        expect -re $prompt
    }
    # TODO handle other cases like fingerprint mismatch here...
}

# assuming the above got us to a prompt...
send -- "cd FIXMESOMEDIR\r"

expect {
    # TWEAK error message may vary depending on shell (try
    # both a not-exist dir and a chmod 000 dir)
    -ex " cd: " { exit 1 }
    -re $prompt {}
}

# assuming the above got us to a prompt and that the cd was
# properly checked for errors...
send -- "echo git pull FIXMEREMOVEDEBUGECHO\r"

expect -re $prompt
interact
3
  • nice answer. You might want to distinguish between the timeout and eof cases with a different exit status. Commented Nov 22, 2016 at 20:22
  • Wow! works great! note sure I get the expect_before thingie but thanks! Commented Nov 23, 2016 at 6:48
  • I just added another send -- "exit\r" in the end to disconnect, works perfect! Commented Nov 23, 2016 at 6:48

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.