1

I'm trying to execute a command which looks like

pass = executeCommand("/usr/bin/openssl rand -base64 8 | tr -d '+' | cut -c1-8")

but pass value is blank in that case. When I leave it not piped as

pass = executeCommand("/usr/bin/openssl rand -base64 8")

it works fine

Method executeCommand looks like

private static String executeCommand(String command) throws Exception {

      StringBuffer output = new StringBuffer();

      Process p;
      try {
         p = Runtime.getRuntime().exec(command);
         p.waitFor();
         BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

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

      }
      catch (Exception e) {
         e.printStackTrace();
         throw new Exception("Could not generate password : " + e.getMessage());
      }

      return output.toString().trim();

   }

Any suggestions how to get that piped version to work?

JackTheKnife
  • 3,795
  • 8
  • 57
  • 117

1 Answers1

2

Try this:

String[] COMPOSED_COMMAND = {
        "/bin/bash",
        "-c",
        "/usr/bin/openssl rand -base64 8 | tr -d '+' | cut -c1-8",};
Process p = Runtime.getRuntime().exec(COMPOSED_COMMAND);
Davide Patti
  • 3,391
  • 2
  • 18
  • 20