0

I need to run some Bash commands in my Java app but all those scripts require sudo permission.

For example

    p = Runtime.getRuntime().exec("sudo /opt/lampp/xampp start");
    p.waitFor();

This doesn't work because I cannot write my sudo password, so I tried:

    p = Runtime.getRuntime().exec("gksu /opt/lampp/xampp start");
    p.waitFor();

And it works! But in some case I have 2 or more commands like (for example):

     p = Runtime.getRuntime().exec("gksu /opt/lampp/xampp apachestart");
     p2 = Runtime.getRuntime().exec("gksu /opt/lampp/xampp mysqlstart");
     ....

And user have to write sudo password 2/3 time. I created a bash file so I can execute this file with a single gksu. But the problem remains because user have to insert sudo password another time when I will recall this function.

At the end I tried:

      String sudoPassword = askSudoPassword();
      p = Runtime.getRuntime().exec("echo " + sudoPassword + 
                                    " && " + "/opt/lampp/xampp apachestart");

But it failed, I tried " | " instead " && " or "echo " + sudoPassword + " ; ....

I also tried to put password with a single quote into the string, but it failed again.

What can I do?

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
Nikolas
  • 178
  • 1
  • 2
  • 10
  • http://stackoverflow.com/questions/18708087/how-to-execute-bash-command-with-sudo-privileges-in-java – Xin Meng Feb 07 '17 at 12:14
  • 2
    Using [this answer idea](http://stackoverflow.com/a/18708281/4391450) to reuse the password previously asked – AxelH Feb 07 '17 at 12:17
  • Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask. Also see [Where do I post questions about Dev Ops?](http://meta.stackexchange.com/q/134306) – jww Feb 07 '17 at 23:07

0 Answers0