一般的想法可以是生成 ssh 并关闭连接的过程,该过程将保持范围本地的连接,因此全局 spawn_id 根本不会受到影响。
#!/usr/bin/expect
proc isHostAlive {host user pwd} {
# We escaped the `$` symbol with backslash to match literal '$'
# Commonly used prompt types
set prompt "#|%|>|\\\$"
set timeout 60
spawn ssh $user@$host
expect {
timeout {return FAIL}
"(yes/no)" {send "yes\r";exp_continue}
"password:" {send "$pwd\r";exp_continue}
-re $prompt
}
set msg "Hello World"
send "echo $msg\r"
expect {
timeout {return FAIL}
"\r\n$msg"
}
send "exit\r"
expect {
timeout {return FAIL}
eof
}
return PASS
}
# Lists to maintain the each host's information
set serverList {server1 server2 server3}
set userList {user1 user2 user3}
set pwdList {pwd1 pwd2 pwd3}
# Looping through all the servers and checking it's availability
foreach server $serverList user $userList pwd $pwdList {
puts "\n==>Status of $server : [isHostAlive $server $user $pwd]\n"
}
使用exp_continue,即使任何主机没有密码,我们也可以处理。基本上exp_continue 将导致expect 再次运行。因此,在提到的短语中,无论哪个来,都会被处理。即如果expect看到(yes/no),它将发送yes,如果expect看到password,它将发送密码值等等。然后expect会再次继续等待整组词组。
我之所以添加yes/no是因为假设需要保存主机的RSA指纹。
成功登录后,我正在回显Hello World 并期待回显消息。如果你注意到了,我在期望语句中使用了\r\n$msg。为什么我们在这里需要\r\n?
这就是原因。每当我们发送期望也会看到的命令时,它也会尝试与之匹配。如果匹配,它将照此进行。
回显命令输出示例
dinesh@dinesh-VirtualBox:~/stackoverflow$ echo Hello World
Hello World
dinesh@dinesh-VirtualBox:~/stackoverflow$
我们想要的字符串已经在send 命令中可用。因此,为了确保匹配的期望字符串仅来自实际的回显响应,我添加了\r\n,这将帮助我们匹配必要的内容。
然后在proc 的最后,我发送exit 命令,它将关闭ssh 连接并匹配相同的eof(文件结尾)。在各种失败情况下,该过程将返回FAIL。