开发者

How can I account for connection failure using expect for ssh log-on automation?

I have a shell script that works fairly well for automating my ssh connections and for anything else that I would like to do via ssh. I'm very unsatisfied with the results, however, when host can't be found or if connection is refused. If the host cannot be found, upon timeout send prints my password onto the screen... no good. I've gotten around t开发者_开发百科his by adding an infinite timeout < set timeout -1 >. When connection is refused; however, I get a message about how connection was refused and that there was an error sending, etc... and my password is printed as well. Is there a way to tell my script that if exact expect is not met then don't proceed to send, to just ctrl+c? The following is the relevant part of my shell script: (used in bash, by the way) Thanks in advance.

    expect -c "
    spawn ssh $USER@$HOST
    expect -exact \"$USER@$HOST's password:\"
    send \"$PASS\r\"
    interact"


The answer is to expect the timeout keyword. If none of the patterns match, then the timeout condition occurs -- of course, you can't set the timeout value to -1: set it to a reasonable number of seconds.

Instead of cramming a large-ish script into the -c argument, put it into a file

#! /usr/local/bin/expect -f
set host [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
# or, foreach {host user password} $argv {break}

spawn ssh $user@$host
expect {
  -re {password: $} {send "$password\r"}
  timeout {error "ssh connection timed out!"}
}
interact
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜