1

I want to switch user and then launch a command under the new user. Actually my code is

String[] commandToRun2 = {"su","-","jboss", "./jboss-cli.sh -c :shutdown(restart=true)"};
ProcessBuilder pb = new ProcessBuilder(commandToRun2);
pb.directory(new File("/home/jboss/soft/jboss-as-7.1.1.Final/bin/"));
Process p = pb.start();

but I can't make it work.

Jebus
  • 75
  • 1
  • 3
  • 12
  • How exactly does it not work? Is there an Exception in the logs? – VasiliNovikov Dec 14 '15 at 21:13
  • No exception, It just end the process normally but without execute correctly the command. Using the same command under root (without su) it works fine. – Jebus Dec 15 '15 at 11:30
  • Did you test your `su` command manually? Do you launch your java application from the same user as you tested `su`? – VasiliNovikov Dec 15 '15 at 12:26
  • yes I did. I have 2 Jboss instances, 1 under "root" user and another under "jboss" user. I need to use "su" command to launch the application under jboss. – Jebus Dec 15 '15 at 12:58
  • What if you `Thread.sleep` for 1 minute to give the created process some time? – VasiliNovikov Dec 15 '15 at 13:00
  • Also, try to split your problem into simpler parts. Try to execute `touch /home/jboss/testFile` first. Manually and from inside the java app that is launched from root. If it succeeds, try `su - jboss touch /home/jboss/testFile`. Find out which step starts to fail. – VasiliNovikov Dec 15 '15 at 13:02
  • // `Thread.sleep(60000L)` is meant to be inserted after `pb.start()`. – VasiliNovikov Dec 15 '15 at 15:07
  • @Jebus how did you managed to provide the password for that user from java code? – HyperioN Jul 12 '17 at 06:05
  • The user hadn't password – Jebus Jul 13 '17 at 18:56

1 Answers1

1

According to this SuperUser answer, your call to su doesn't appear to be quite right.

From that question, the su command should have the form

su [username] -c "[command]"

So, try the following instead:

String[] commandToRun2 = {"su", "jboss", "-c", "./jboss-cli.sh -c :shutdown(restart=true)"};

Incidentally, it may be helpful to log any output written to the process's standard output and standard error. If there's an error, you'll then be able to see what the error is, and if the process generates a lot of output, reading the output will prevent output buffers from filling and blocking the process. This answer demonstrates how you can do this.

Community
  • 1
  • 1
Luke Woodward
  • 63,336
  • 16
  • 89
  • 104