我从bash脚本调用了Expect脚本。 Expect脚本产生 一个ssh会话并运行一个远程命令。我想要一个返回码 我的shell脚本中可用的远程命令。
# !/bin/sh
expect -f remote.exp 192.168.1.100 user pass 10.10.10.1
# here I want to analyze exit status of remotely invoked command
期望脚本在下面,这是我丑陋的解决方法:
#!/usr/bin/expect
set timeout 20
set box [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set target [lindex $argv 3]
spawn ssh -l $user $box
expect "*password:"
send "$password\r\n"
expect "*#"
send "ping -c1 $target\r\n"
expect "*#"
send "echo $?\r"
expect {
"0\r" { puts "Test passed."; }
timeout { puts "Test failed."; }
}
expect "*#"
PS。我读到expect_out可能会对我有所帮助,但我没有成功。任何帮助 将不胜感激!感谢。
答案 0 :(得分:3)
我尝试了以下内容,它适用于Mac:
#!/usr/bin/expect
# Process command parameters
foreach {host user password target} $argv {break}
set command "ping -c 1 $target"
# Log in
spawn ssh -l $user $host
expect -nocase "password:"
send "$password\r"
# Send the command
expect "$ "
send "$command\r"
# Echo the return code, the key here is to use the format code=X instead
# just a single digit. This way, Expect can find it
expect "$ "
send "echo code=$?\r"
# Analyze the result
set testResult "Test failed."
expect {
"code=0" { set testResult "Test passed." }
}
puts "$testResult"
# Done, exit
expect "$ "
send exit
请注意一些差异: