Shell.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package au.pfip;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.InputStreamReader;
  5. import java.util.ArrayList;
  6. public class Shell {
  7. /** Returns null if it failed for some reason.
  8. */
  9. private static ArrayList<String> command(final String cmdline) {
  10. try {
  11. Process process =
  12. new ProcessBuilder("/usr/bin/bash", "-c", cmdline)
  13. .redirectErrorStream(true)
  14. .directory(new File("."))
  15. .start();
  16. ArrayList<String> output = new ArrayList<>();
  17. BufferedReader br = new BufferedReader(
  18. new InputStreamReader(process.getInputStream()));
  19. String line;
  20. while ( (line = br.readLine()) != null )
  21. output.add(line);
  22. //There should really be a timeout here.
  23. if (0 != process.waitFor())
  24. return null;
  25. return output;
  26. } catch (Exception e) {
  27. logging.error("RuntimeException(e) ~ " + e);
  28. return null;
  29. }
  30. }
  31. public static boolean check(String cmd, String needle)
  32. {
  33. String cmdOutput = test(cmd);
  34. return cmdOutput.contains(needle);
  35. }
  36. public static void runCmd(String cmd)
  37. {
  38. test(cmd);
  39. }
  40. // --Commented out by Inspection START (4/2/25, 10:02 pm):
  41. // public static boolean checkMulti(String cmd, String needle)
  42. // {
  43. // String cmdOutput = test(cmd);
  44. // return cmdOutput.contains(needle);
  45. // }
  46. // --Commented out by Inspection STOP (4/2/25, 10:02 pm)
  47. private static String test(String cmdline) {
  48. ArrayList<String> output = command(cmdline);
  49. StringBuilder reply = new StringBuilder();
  50. if (null == output) {
  51. return "";
  52. }
  53. else {
  54. for (String line : output) {
  55. reply.append(line);
  56. }
  57. }
  58. return reply.toString();
  59. }
  60. }