从Rhino脚本中访问Java特权操作

时间:2012-05-30 10:17:19

标签: java javascript

如何从Java中的Rhino中运行的JavaScript执行本地文件?我将考虑在Rhino环境中工作的任何方法。我目前对这个问题的探索如下。

我是通过java.lang.Runtime.exec尝试这个,在Mozilla“Scripting Java”教程的帮助下我可以访问它。但是,这是一个受限制的操作,因此直接调用它会产生访问控制异常。

要解决这个问题,我需要使用AccesController.doPrivileged方法。下面是在Java中使用它的一个例子;

AccessController.doPrivileged(new PrivilegedAction() {
          public Object run() {
             // Code goes here. Any permission checks within this
             // run method will require that the intersection of the
             // callers protection domain and the snapshot's
             // context have the desired permission.
          }

路障正在javascript中复制PrivilegedAction的构造。

var ourRuntime = Packages.java.lang.Runtime.getRuntime();
//ourRuntime.exec("notepad.exe") //will raise Access Control Exception
var controller = Packages.java.security.AccessController.doPrivileged
var action = new Packages.java.security.PrivilegedAction(ourRuntime.exec("notepad.exe"))         // somehow make this wwrk
controller.doPrivileged(action)

Mozilla Scripting Java

java.securit.AccessController

2 个答案:

答案 0 :(得分:0)

Rhino受Java 6脚本API支持,因此您可以使用doPrivileged包装脚本的eval并使用必要的权限执行整个脚本。与doPrivileged结合的java脚本API示例为here

答案 1 :(得分:0)

我以这种方式成功启动了KWrite(例如)。我基本上将Runtime对象暴露给嵌入式JavaScript解释器。

public class RunBasicScript {

public static void main(String[] args) {

    // Get a handle to the JavaScript context
    Context cx = Context.enter();

    try 
    {
        // Set up the standard JavaScript objects
        // like Object, Function etc.
        Scriptable scope = cx.initStandardObjects();

        // Make Runtime.getRuntime available to our JavaScript code
        Object exec = Context.javaToJS(Runtime.getRuntime(), scope);
        ScriptableObject.putProperty(scope, "exec", exec);

        // Build our awesome script
        String script = "exec.exec('kwrite');";

        // Now we execute the script
        Object obj = cx.evaluateString(scope, script, "Testing", 1, null);
    } 
    catch (Exception e) 
    {
        System.err.println("Error : " + e);
    }
    finally 
    {
        // We need to exit the Context.
        Context.exit();
    }
}

}