From 2056a2153855c4ed330a760e6c0838d050c6c926 Mon Sep 17 00:00:00 2001 From: brunoais Date: Sat, 16 Apr 2022 14:44:16 +0100 Subject: [PATCH] Add shell script execution to the server --- .../java/com/genymobile/scrcpy/Command.java | 42 ++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/server/src/main/java/com/genymobile/scrcpy/Command.java b/server/src/main/java/com/genymobile/scrcpy/Command.java index 0ef976a6..cd5bb89b 100644 --- a/server/src/main/java/com/genymobile/scrcpy/Command.java +++ b/server/src/main/java/com/genymobile/scrcpy/Command.java @@ -1,7 +1,9 @@ package com.genymobile.scrcpy; -import java.io.IOException; +import java.io.*; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Scanner; public final class Command { @@ -17,6 +19,44 @@ public final class Command { } } + public static void execShellScript(String script, String... args) throws IOException, InterruptedException { + + ArrayList cmd = new ArrayList<>(); + cmd.add("sh"); + cmd.add("-s"); + cmd.addAll(Arrays.asList(args)); + + Process process = Runtime.getRuntime().exec(cmd.toArray(new String[]{})); + BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream())); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + BufferedWriter input = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); + input.write(script); + input.close(); + + StringBuilder fullLines = new StringBuilder(); + String line; + if (Ln.isEnabled(Ln.Level.DEBUG)) { + while ((line = output.readLine()) != null) { + fullLines.append(line); + fullLines.append("\n"); + } + Ln.d("Custom script output:\n---\n" + fullLines + "\n----\n"); + } + fullLines = new StringBuilder(); + if (Ln.isEnabled(Ln.Level.WARN)) { + while ((line = err.readLine()) != null) { + fullLines.append(line); + fullLines.append("\n"); + } + Ln.w("Custom script err:\n---\n" + fullLines + "\n----\n"); + } + + int exitCode = process.waitFor(); + if (exitCode != 0) { + throw new IOException("Custom script with args: " + Arrays.toString(args) + " returned with value " + exitCode); + } + } + public static String execReadLine(String... cmd) throws IOException, InterruptedException { String result = null; Process process = Runtime.getRuntime().exec(cmd);