通过ssh连接的Shell脚本与重试

时间:2015-06-04 23:01:54

标签: linux bash shell ssh expect

我正在寻找一种方法来创建一个shell脚本,用于使用ssh协议,用户,密码和端口连接到远程机器。最终脚本必须按时重试连接至少三次。

我找到了很多关于如何使用expect脚本或shell脚本运行expect来获取连接或测试连接的示例,但是没有人在超时时进行重试连接。

我正在粘贴一些我用来获取ssh连接的样本,就像我正在使用的脚本一样。我的问题是如何在超时时重试?

非常感谢

#!/usr/bin/expect -f
spawn ssh aspen
expect "password: "
send "PASSWORD\r"
expect "$ "
send "ps -ef |grep apache\r"
expect "$ "
send "exit\r"

1 个答案:

答案 0 :(得分:0)

我认为关键是期待超时事件。代码可能会像这样

expect {
    timeout {
        send_user "retry"
        spawn ssh apen
        exp_continue
    }
    "continue connecting (yes/no)?" {
        send "yes\r"
        exp_continue
    }
    -re "\[Pp]assword:" {
        send -- "$password\r"
    }
    "Host key verification failed." {
        expect_after;       # do not exit on eof
        if {[regexp -line "^Offending key in.*\.ssh/known_hosts:(\[0-9]*)" \
                 $expect_out(buffer) dummy lineNum] ==1} {
            send_user "Delete stored finger print? (n/y) ";
            expect_user {
                -re "\[yY]" {exec sed -i "${lineNum}d" [glob "~/.ssh/known_hosts"]}
                -re "\[^Yy]" {}
            }
            exit 0
        }
    }
}

请注意,“超时”行未经过测试。我从我的代码中复制了这个片段,其中超时行是“timeout {exit}”。

我不太确定在expect子句中生成新的ssh是否有效。但是,至少你可以捕获超时事件并将其置于循环中