I'm using ProcessBuilder to execute bash commands:
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
Process pb = new ProcessBuilder("gedit").start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But I want to make something like this:
Process pb = new ProcessBuilder("sudo", "gedit").start();
How to pass superuser password to bash?
("gksudo", "gedit")
will not do the trick, because it was deleted since Ubuntu 13.04 and I need to do this with available by default commands.
EDIT
gksudo came back to Ubuntu 13.04 with the last update.
I think you can use this, but I'm a bit hesitant to post it. So I'll just say:
Use this at your own risk, not recommended, don't sue me, etc...
My solution, doesn't exposes the password in the command line, it just feed the password to the output stream of the process. This is a more flexible solution because allows you to request the password to the user when it is needed.
Once you spawn a process you can extract the input and output streams. Just feed the password to the output stream (you output it into the proccess's input). So the code would look something like -
Do not try to write a system password plainly in a file, especially for a user that have the sudo privilage, just as @jointEffort answered, privilege issued should be solved by system administrators not by app writers.
sudo
allow you to grant privileges for specific command to specific user, which is precisely enough, check this postand you can choose to manage the privilege in a separated file other than the main sudoers file if you want just append
#includedirs /etc/sudoers.d/
in the main/etc/sudoers
file(most Linux distributions have already done that) and make a file likeifconfig-user
with:Another thing, remember to edit the config file with
visudo
in case you lost control of your system when there is syntax error.Edit /etc/sudoers with visudo and grant your user a NOPASSWD right for a specific script:
username ALL=(ALL) NOPASSWD: /opt/yourscript.sh
I know this is an old thread but i just want to put this here:
you can use
sudo -S *command*
as a command that you pass to create the Process instance. Then get the output stream and write the password to it, and add at the end of it a new line and a c. return (\n\r
). The return may not be required but i passed it just in case. Also it is a good idea to flush the stream, to make sure everything is written to it. I've done it a few times and it works like a charm. And DO NOT forget to close streams :).