且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

期望脚本用于远程SSH登录和执行命令

更新时间:2023-11-11 20:41:40

在完成密码和真实性检查之后,您应该使用exp_continue重新进入Expect循环.请尝试以下操作:

You should be using exp_continue to reenter your Expect loop after the password and authenticity checks are done. Try the below:

#!/usr/bin/expect

set prompt "pi@raspberrypi ~ $ "
spawn ssh [lindex $argv 1]@[lindex $argv 0]

set timeout 5
expect {
    timeout {
        puts "Connection timed out"
        exit 1
    }

    "yes/no" {
        send "yes\r"
        exp_continue
    }

    "assword:" {
        send -- "[lindex $argv 2]\r"
        exp_continue
    }

    "$prompt" {
        send "ls -la\r"
    }
}

这是Don Libes从 Exploring Expect 中获得的关于exp_continue的摘录:

This is an extract taken from Exploring Expect regarding exp_continue by Don Libes:

当作为Expect操作执行时,命令exp_continue使控制在当前Expect命令中继续进行. Expect会继续尝试匹配该模式,但是从上次匹配后该模式会中断. Expect有效地重复了它的搜索,就好像再次被调用一样.

When executed as an Expect action, the command exp_continue causes control to be continued inside the current Expect command. Expect continues trying to match the pattern, but from where it left off after the previous match. Expect effectively repeats its search as if it had been invoked again.