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.
As the new user, verify that you can use sudo by adding "sudo" to the beginning of the command that you want to run with superuser privileges. The first time you use sudo in a session, the system will prompt you for the password of the user account. Enter the password to proceed.
In Linux, the sudo command allows us to execute a command or script as the superuser. However, by default, the sudo command works in an interactive mode.
Running a Specific Script as Another User. Before we can execute scripts as other users with sudo, we'll need to add the current user to the sudoers file. To do that, we'll use the visudo command to safely edit the /etc/sudoers file. The command above echo the rule and pipe the rule into the visudo command.
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...
public static void main(String[] args) throws IOException { String[] cmd = {"/bin/bash","-c","echo password| sudo -S ls"}; Process pb = Runtime.getRuntime().exec(cmd); String line; BufferedReader input = new BufferedReader(new InputStreamReader(pb.getInputStream())); while ((line = input.readLine()) != null) { System.out.println(line); } input.close(); }
Edit /etc/sudoers with visudo and grant your user a NOPASSWD right for a specific script:
username ALL=(ALL) NOPASSWD: /opt/yourscript.sh
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With