Linux期望发送奇怪的结构

时间:2012-12-04 14:21:41

标签: expect

我想知道如何工作。 AFAIK期望脚本包含“expect”和“send”语句。因此,对于屏幕上显示的每个适当的“期望”语句,调用“发送”语句。命令“交互”也意味着控制被传递回用户并且他能够与终端交互。如果我错了,请纠正我。这两个陈述就像一个魅力。

第一

#!/usr/bin/expect
spawn ssh -q localhost;

# Handles following message: "Are you sure you want to continue connecting (yes/no)?"
expect "yes";
send "yes\r";
interact;

第二

#!/usr/bin/expect
spawn ssh -q localhost;

# Handles following message: "pista@localhost's password:" 
expect "assword";
send "password\r";
interact;

我在互联网上发现类似下面的代码应该将这两个例子合并为一个:

#!/usr/bin/expect
spawn ssh -q localhost "uname -a";
expect {
    "*yes/no*" { send "yes\r" ; exp_continue }
    "*assword:" { send "password\r"; interact }
}

但是这个例子在sucesfull登录后立即退出(似乎“interactive”在这里不起作用,请参见下面的输出)

[pista@HP-PC .ssh]$ ./fin.exp
spawn ssh -q localhost uname -a
pista@localhost's password: 
Linux HP-PC 3.6.6-1.fc16.x86_64 #1 SMP Mon Nov 5 16:56:43 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
[pista@HP-PC .ssh]$ set | grep SHLV
SHLVL=2

三个问题:

  1. 那些奇怪的期望语法是什么意思,只有可能的解释是,在这个“大”期望中没有强调模式顺序?
  2. 你能否澄清一下exp_continue究竟在做什么,在我看来像“goto”语句期待哪个调用了这个?
  3. 为什么不在这里互动?
  4. 非常感谢

1 个答案:

答案 0 :(得分:1)

1。此语法意味着您使用连续的expect语句,这更容易。例如,如果SSH失败,这将尝试SSH或telnet

#!/usr/bin/expect
set remote_server [lrange $argv 0 0]
set timeout 10
spawn ssh -M username@$remote_server
while 1 {
  expect {
    "no)?"      {send "yes\r"}
    "denied" {
                log_file /var/log/expect_msg.log
                send_log "Can't login to $remote_server. Check username and password\n";
                exit 1
             }
    "telnet:" {
                log_file /var/log/expect_msg.log
                send_log "Can't connect to $remote_server via SSH or Telnet. Something went definitely wrong\n";
                exit 2
              }
    "failed" {
                log_file /var/log/expect_msg.log
                send_log "Host $remote_server exists. Check ssh_hosts file\n";
                exit 3
             }
    timeout {
                log_file /var/log/expect_msg.log
                send_log "Timeout problem. Host $remote_server doesn't respond\n";
                exit 4
            }
    "refused" {
                log_file /var/log/expect_msg.log
                send_log "Host $remote_server refused to SSH. That is insecure.\n"
                log_file
                spawn telnet $remote_server
              }
    "sername:" {send "username\r"}
    "assword:" {send "password\r"}
    "#"        {break}
  }
}

2. exp_continue告诉我们期望“继续期待”,即继续事件处理。如果没有此指令,您的期望{...}块将停止。在上面的例子中,它是行:

"#" {break}

首先它从while循环中断,然后没有exp_continue它停止执行expect {...}块并继续执行下一条指令(上例中未显示)。

3。您的代码中有错误。我稍微修改了你的代码,使它工作。

#!/usr/bin/expect
spawn ssh -q localhost
expect {
    "*yes/no*" { send "yes\r" ; exp_continue }
    "*assword:" { send "password\r"; exp_continue;}
    "~" {send "uname -a\r"; interact;}
}