Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute bash command with sudo privileges in Java?

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.

like image 395
Vare Zon Avatar asked Sep 09 '13 22:09

Vare Zon


People also ask

How do I use sudo privileges?

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.

Can you use sudo in script?

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.

How do I run a sudo script?

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.


2 Answers

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(); } 
like image 172
Erik Pragt Avatar answered Sep 20 '22 21:09

Erik Pragt


Edit /etc/sudoers with visudo and grant your user a NOPASSWD right for a specific script:

username ALL=(ALL) NOPASSWD: /opt/yourscript.sh

like image 28
JointEffort Avatar answered Sep 24 '22 21:09

JointEffort