【问题标题】:How test SSH connectivity with expect script如何使用期望脚本测试 SSH 连接
【发布时间】:2015-11-18 20:32:47
【问题描述】:

我有 Linux red-hat 机器 - 5.X 版

我想创建一个期望脚本来验证远程机器的 ssh 登录是否成功

我的测试只是在远程登录时获得密码提示(我不想输入密码)

就像测试 ssh 连接性

到目前为止,我创建的是以下脚本

所以如果我得到密码提示,那么脚本需要返回 0

如果不是,那么脚本需要返回 1

我的脚本的问题在于 - 即使 ssh 登录失败,脚本也会返回 0(没有密码提示)

 #!/usr/bin/expect


 set LOGIN      [lindex $argv 0]
 set PASSWORD   [lindex $argv 1]
 set IP         [lindex $argv 2]




 set timeout 10
 spawn ssh -o StrictHostKeyChecking=no $LOGIN@$IP
 expect -re "(Password:|word:)"
 exit 0
 expect {
     timeout {error "incorrect password"; exit 1}
 eof
 }

请告知如何更新我的脚本?

【问题讨论】:

  • 您将永远无法通过 shell 脚本进行 SSH 键盘交互式登录。密码必须来自键盘。请改用基于密钥的身份验证。
  • Expect 模拟键盘。是的,expect 可以做到。
  • Kuhn - 如果 expect 可以做到这一点,您能否通过更新我的代码来告诉我需要更改哪些内容才能验证 SSH 登录?
  • 那么你对expect -re "(Password:|word:)"exit 0这两行有什么期望呢?没有将密码发送到键盘的说明。代码只是在提示符中检测到某些内容并退出。
  • 为了完整起见,现在有 sshpass 将取代此类预期 scipts。参见例如askubuntu.com/questions/282319/how-to-use-sshpass

标签: linux bash tcl expect


【解决方案1】:

您必须将条件包含在一个 expect 中,

set timeout 10
spawn ssh -o StrictHostKeyChecking=no $LOGIN@$IP
expect {
    timeout {puts "Timeout happened";exit 0}
    eof {puts "EOF received"; exit 0}
    -nocase "password:" {puts "SSH connection is alive for the host $IP"; exit 1}
}

查看与您的问题相似的here

【讨论】:

  • -nocase 是什么意思??
  • 这是一个标志,使单词password:的字符串匹配不区分大小写。
  • ok,我有几点意见(需要将exit 0改为exit 1,exit 1改为exit 0),因为0表示ok状态
  • 第二个 - 需要将 -nocase "password:" 更改为期望 -re "(Password:|word:)" 因为这个提示可以在远程机器上区分
  • 这就是-nocase 的全部意义所在。它可以匹配password的不区分大小写的模式。
【解决方案2】:

sshlogin.expect:

set timeout 60

spawn ssh [lindex $argv 1]@[lindex $argv 0]

expect "yes/no" { 
   send "yes\r"
   expect "*?assword" { send "[lindex $argv 2]\r" }
   } "*?assword" { send "[lindex $argv 2]\r" }

interact

用法:

sshlogin.expect <host> <ssh user> <ssh password>

【讨论】:

  • 不工作 - 因为超时未激活(不返回 0 或 1)它卡住了
  • 最好将“是/否”也移到内部期望中,因为它通常只会被询问一次,而不会再被询问
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 2015-04-11
  • 2015-07-30
  • 1970-01-01
  • 2014-10-14
相关资源
最近更新 更多