ConsoleApi.java 1.59 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package web.multitask.trismegistoservices.api;

import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("console")
public class ConsoleApi {
    @PostMapping("/public/command")
17
    public ResponseEntity<?> pull(@RequestBody String jsonBody) {
18 19

        JSONObject json = new JSONObject(jsonBody);
20 21 22
        String command = json.optString("command", "");
        if (json.optBoolean("sudo", false)) {
            command = "echo '" + json.optString("password", "") + "' | sudo -S " + command;
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
        }
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", command)
                    .directory(new File(json.optString("path", "")))
                    .redirectErrorStream(true);
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            int exitCode = process.waitFor();

            return ResponseEntity.ok(
40 41
                    "Exit Code: " + exitCode + "\n" +
                            output.toString());
42 43 44 45 46
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}