Search code examples
javabashprocessbuilder

How to execute shell commands as root in Java


I'm working on a cross-platform installation utility written in Java. I would like to be able to execute shell commands, for example "apt-get ..." on Linux. I'm using the ProcessBuilder API for this purpose.

Unfortunately, some commands require root privileges. I would like to execute the following shell command as root:

bash -c apt-get install -y [some package]

If I try to add "sudo" before "apt-get" nothing works because there is no terminal "sudo" can get the password from.

What should I do in order to ask the user for a password and then execute the above mentioned shell command?

A short code snippet would be very appreciated! Thanks in advance! Max


Solution

  • You could run gksudo <your command> but this ties your application to a certain UI, e.g. gnome, kde, etc.