2011-06-14 15 views
1

我有一个从bash脚本调用的Expect脚本。 Expect脚本会产生一个ssh会话 并运行一个远程命令。我想在我的shell脚本中使用远程命令的返回码 。在Expect中得到远程命令的结果

# !/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可能对我有帮助,但我没有得到它的工作。任何帮助 将不胜感激!谢谢。

回答

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 

注意一些区别:

  1. 我的系统上的shell提示符是 “$”
  2. 我只发\ r,而不是\ r \ n。我不知道它的问题
  3. 我通过发送“退出”
+1

+1退出SSH会话:在“'$'”很多壳的提示*年底*,并预计仍然会与它们匹配。很好,但尽管如此。发送'\ r'完全正确。 (我会配置SSH会话的RSA密钥以避免密码,但这并不总是可能的。唉。) – 2011-06-15 08:17:28

+0

@Donal:关于RSA密钥的优点。我自己有,但正如你所说,并不总是可能的。 – 2011-06-15 19:05:53