简体   繁体   中英

Java Linux Shell Application

So I just received a task for creating a Java Shell App, without using any 3rd party libraries, and without using Runtime.exec() or ProcessBuilder APIs.

I don't want the solution (obviously I want to do this myself) but I do need a hint how to do this? I want the app to open a shell prompt which will accept various commands with usage of JDK 8 (Nashorn?).

Thanks!

Not really clear what you want to achieve. If you want to run a Nashhorn shell you can achieve it like this (Java 8)

import jdk.nashorn.tools.Shell;
public class NashornShell {
    public static void main(String[] args) {
        Shell.main(new String[]{ "-scripting"});
    }
}

When you see the Nashorn prompt jjs> you can execute Linux commands...

jjs> $EXEC("ls");

which will list the current directory (using the Linux ls command).

... or execute Java commands ...

jjs> java.lang.System.out.println("foo");

... or execute JavaScript commands ...

jjs> print("foo");

For more information have a look in the nashorn guide .

edit If you want to pass only yourCommand as parameter.

NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(new String[]{"-scripting"});
String yourCommand = "ls";
Object eval = engine.eval("$EXEC(\"" + yourCommand + "\")");
System.out.println(eval);

edit do you think that instead of Nashorn I could just use raw streams directed to the OS from JVM

Following is possible

Commands.java

class Commands {
    public static void main(String[] args) {
        System.out.println("ls");
        System.out.println("whoami");
    }
}

run.sh

#!/bin/sh
java Commands | while read command; do
  echo
  echo "command: $command"
  $command
done

But obviously this is not to recommend when you want to execute the output of Commands :

  • your Java application has no control about the return state of the executed single commands
  • if one command wait for user input your Java application don't know it
  • your Java application has no access to the output produced by the commands
  • all commands are blindly exected
  • and some more downsides

Regardless of what you're trying to do, using nashorn internal class like jdk.nashorn.tools.Shell is not a good idea. With java 9, this package is not an exported package of jdk.scripting.nashorn module. So, with java 9, you'll get package access failure (even in the absence of security manager - as module read/export access check is more like member access check for classes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM