How to run Unix shell script in a java code using ExpectJ tool?

旧城冷巷雨未停 提交于 2019-12-11 06:52:22

问题


This is my hello.sh shell script

VALID_NAME="abcd"

echo "Name: "

read name

if [ "$name" == $VALID_NAME ]; then

echo "correct"

else

echo "unexpected input"

fi

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

This is my Java code

import java.io.IOException;

import expectj.*;

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

    ExpectJ exp = new ExpectJ();
    String command = "sh /root/Desktop/hello.sh";
    Spawn s;
    try {
        s = exp.spawn(command);
        s.expect("Name: ");
        s.send("abcd");
        System.out.println(s.getCurrentStandardOutContents());
        s.stop();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (ExpectJException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
}
}

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

And this is my OUTPUT

Name: //this is wat it asks for

abcd //this is what i give..and nothing happens

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

I've corrected my java code above..


回答1:


In your Java code you look for

s.expect("VALID_NAME=");

yet in your Bash code, you have:

echo "Name: "

It seems like simply changing your Java code to the following should work:

s.expect("Name: ");



回答2:


I've never used ExpectJ, but the start of your error messagesh: hello.sh: No such file or directory suggests that it is unable to find your shell script. Have you tried it with the full path to the script?

String command = "sh /root/Desktop/hello.sh";


来源:https://stackoverflow.com/questions/5702178/how-to-run-unix-shell-script-in-a-java-code-using-expectj-tool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!