如何使用 expect 命令创建 else 语句?

如何使用 expect 命令创建 else 语句?

我有以下预期脚本,如果已知主机不存在,它会添加已知主机。

#!/usr/bin/expect
spawn ssh user@domain "cd /home/user"
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes\r"
interact

我第一次 ssh 进入设备时,脚本运行正常,但是如果我第 n + 1 次 ssh 进入设备,它会抛出一个错误

send: spawn id exp6 not open
    while executing
"send "yes\r""
    (file "./testing_spawn.sh" line 4)

大概是因为它继续期待字符串Are you sure you want to continue connecting (yes/no)?

interact如果该消息没有出现,我该如何告诉脚本呢?

答案1

expect_before仅当“未知主机”问题出现在命令提示符之前时才使用它来匹配该问题:

#!/usr/bin/expect
spawn ssh user@domain
expect_before "*(yes/no)?" {
    send "yes\r"
}
expect "*# "
interact

答案2

尝试这个:

#./test.exp 1.1.1.1

测试.exp

#!/usr/bin/expect -f
set ip [lindex $argv 0]

spawn ssh -q $ip
expect {
  timeout { send_user "\nFailed\n"; exit 1 }
  eof { send_user "\nSSH failure for $ip\n"; exit 1 }
  "Password:" {
    send "password\n"
  }
  "*(yes/no)?*" {
    send "yes\n"
    interact
  }
  "*#" {
    interact
  }
}

相关内容