处理Expect脚本中的多个语句

5

我是Expect脚本的新手。

我编写了一个用于在Linux机器上进行ssh的Expect脚本,但在尝试ssh到不同的Linux机器时遇到了问题。下面是我复制的脚本。

!/usr/local/bin/expect

set LinuxMachine [lindex $argv 0]

spawn ssh root@$LinuxMachine


expect "root@$LinuxMachine's password:"

send "root123\n"

expect "[root@Client_FC12_172_85 ~]#"

send "ls"

interact

当我在命令行中提供 10.213.172.85 时,第4行中的 expect 读作 "root@10.213.172.85's password:" ,并登录成功。

但是有些 Linux 系统会期望其他形式。

The authenticity of host '10.213.172.108 (10.213.172.108)' can't be established.
RSA key fingerprint is da:d0:a0:e1:d8:7a:23:8b:c7:d8:40:8c:b2:b2:9b:95.
Are you sure you want to continue connecting (yes/no)

在这种情况下,脚本将无法运行。
如何在一个Expect命令中有两个Expect语句?
2个回答

11

在这种情况下,您可以使用exp_continue:

expect {
      "Are you sure you want to continue connecting (yes/no)" {
            send "yes\r"
            exp_continue
      }
      "root@$LinuxMachine's password:" {
            send "root123\r"
            expect "[root@Client_FC12_172_85 ~]#"
            send "ls\r"
            interact
      }
}
在上面的代码块中,Expect模块会等待是yes/no问题还是要求输入密码的提示。如果是后者,它将继续提供密码、等待提示、发送'ls'指令并返回控制权。
如果是前者,它将回答'yes'并重复Expect模块,准备寻找密码提示(或者甚至是yes/no问题,不过你不需要这样做)。
我还建议在每个expect选项无法匹配时使用具有意义的超时消息,但上面的代码应该可以工作。
顺便说一下,你不想在脚本中设置root密码...我建议使用ssh密钥身份验证。

-1

我们喜欢称之为“长时间登录”。有一些ssh选项不会检查主机密钥:

send -- "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username@host\n"
expect {
        "Password" {
                send -- "$passwd\n"
        }

Bash脚本的一部分调用expect设置密码:

echo -n "Enter LDAP password: "
read -s passwd
echo

让我们不要关闭保护我们安全的系统。 - Graham Leggett

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接