期望脚本+期望错过发送字符串+延迟问题

时间:2012-02-24 12:23:09

标签: linux bash shell ksh expect

我编写了active.ksh脚本(基于expect),以便自动登录到某台Solaris机器并执行hostname命令(登录虚拟IP以验证哪个主机名是活动机器 - 我有两个集群solaris机器)

问题出在 expect ; expect发送密码字符串(pass123)并且它错过了密码问题,它仍然等待密码。

实际上密码问题后输入了密码(pass123)。在大多数情况下,expect脚本工作正常,但有时它会丢失密码。

问题的例子

 ./active.ksh
 spawn ssh 10.10.18.61
 sh: /usr/local/bin/stty: not found
 This computer system, including all related equipment, networks and network devices      (specifically including Internet access),is provided only for authorized uss
 Password:        * my remark - pass123 string was missed the Password Question        pass123
 Password: 

THE SCRIPT

  more active.ksh  



  #!/bin/ksh

  VIP_ADDRESS=10.10.18.61


  expect_for_verify_which_active_machine=`cat << EOF
  set timeout -1
  spawn  ssh   $VIP_ADDRESS 
  expect {
  ")?"   { send "yes\r"  ; exp_continue  }
  Password:  {send "pass123\r"}
  }
  expect >  {send "hostname\r"}
  expect >    {send exit\r}
  expect eof
  EOF`


  expect -c  "$expect_for_verify_which_active_machine"

正确结果的例子

  ./active.ksh 
  [Friday, February 24, 2012  2:32:06 PM IST] INFO Verify which is active SMU machine 
  spawn ssh 10.10.18.61
  sh: /usr/local/bin/stty: not found
  This computer system, including all related equipment, networks and network devices       (specifically including Internet access),is provided only for authorized uss
  yes
  Password: 
  Last login: Fri Feb 24 14:32:06 2012 from smu1a
  This computer system, including all related equipment, networks and network devices       (specifically including Internet access),is provided only for authorized uss
  solaris1:/ ROOT > hostname
  solaris1
  solaris1:/ ROOT > exit

  logout
  Connection to 10.10.18.61  closed.

1 个答案:

答案 0 :(得分:0)

使用empty编写此流程可能会更容易。它是一个类似于期望的小型实用程序,但在某些情况下更方便。您可以使用它只是将文本输入应用程序&#34;,您可以忽略应用程序的提示(尽管您不必这样做)。登录到远程计算机并执行hostname可能如下所示:

./empty -f -L templog ssh 10.10.18.61 hostname
echo YOUR_SECRET_PASSWORD | ./empty -s -c
cat templog

第一个在后台启动您的命令。另一个从stdin发送数据(您的密码)。整个会话(包括密码!)将记录到文件templog,您还可以在其中找到hostname的结果。还有一些更精细控制的机制,但它们可能有点难以设置。

正如有些人已经指出的那样,ssh密钥是要走的路,这只是一种丑陋且不安全的解决方法(由于shell历史被保留,用户能够在{{{{{{{{ 1}}结果,在我的示例中,密码另外保存在ps等)。