2011-04-20 54 views
0

这是我的脚本ExpectJ冒险

echo "Name:" 
read name 
if [ "$name" == "abcd" ]; then 
    echo "correct username" 
    echo "Password:" 
    read password 
    if [ "$password" == "pwd" ]; then 
     echo "Hello" 
    else 
     echo "Wrong password" 
    fi 
else 
    echo "wrong username" 
fi 

================================ =================================================

这是我的Java代码

import java.io.IOException; 
import java.util.*; 

import expectj.*; 

public class Trial { 
    public static void main(String[] args) { 

     ExpectJ exp = new ExpectJ(); 
     String command = "sh /root/Desktop/hello.sh"; 
     Spawn s = null; 
     try {   
      s = exp.spawn(command);   
      s.expect("Name:"); 
      s.send("abcd\n"); 
      System.out.println("Current status: "+s.getCurrentStandardOutContents());   
      s.expect("correct username"); 
      s.expect("Password:"); 
      s.send("pwd\n"); 
      s.expect("Hello"); 
      System.out.println("final output: " + s.getCurrentStandardOutContents()); 
      System.out.println("Possible errors: " + s.getCurrentStandardErrContents()); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      System.out.println("ioe\n"); 
     } catch (TimeoutException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      System.out.println("toe\n"); 
     } finally { 
      if (s != null) 
       s.stop();   
     }  
    } 
} 

=================================== =========================================

这是我OUTPUT

Name: 
Current status: Name: 
correct username 
Password: 

================================== ==========================================

它没有进一步发展。其并无终止或者..我不知道为什么..

回答

0

我得到it..2连续s.expect()语句不能work..So摆脱它,一个\ n可以添加..

在这种情况下

s.expect(“正确的用户名”);
s.expect(“Password:”);

未绑定到work.So,应该逐个

s.expect更换(“正确的用户名\ n密码:”); //这将工作

1

是否在您发表评论这一行它的工作:

System.out.println("Current status: "+s.getCurrentStandardOutContents()); 

也许应用是“期待”值"correct username",但看到"Current status: Name:“而不是(”调试“行的输出)。不是jExpert的专家,但是如果该工具只是重定向并监视System.out,它将看到脚本输出以及打印到控制台的所有内容。

+0

是该行的作品,因为它的印刷输出。我猜这是没有问题的..因为控制是来s.expect(“密码:”); ,但它没有成功地从脚本中获取pwd ..我不明白为什么会发生这种情况。 – hari 2011-04-20 12:46:02

+0

控制权不是来自s.send(“pwd \ n”); – hari 2011-04-21 05:05:12