1

I have a requirement where I need to run a script in ubuntu with sudo on click of a button in swing UI.

In mac I just use the open command with Runtime.getRuntime.exec("open appname.app")

and it launches a terminal asking me for the password and executes the script but in linux it doesnt work that way.

I've tried the solution in How to execute bash command with sudo privileges in Java? but didn't work for me.

public static void main(String[] args) throws IOException {

    String[] cmd = {"/bin/bash","-c","echo mysudopassword| sudo -S <path of my script>"};
    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();
}

Even tried it this way as below

{"/bin/bash","-c","echo \"password\"| sudo -S ls"};

Is it possible to pass the password to sudo and then launch the script or open a terminal asking for the password and then launch it ?

I'm using java8 with ubuntu 18.04

Abbas
  • 3,144
  • 2
  • 25
  • 45
  • 2
    Maybe try *-A Normally, if sudo requires a password, it will read it from the user’s terminal. If the -A (askpass) option is specified, a (possibly graphical) helper program is executed to read the user’s password and output the password to the standard output. If the SUDO_ASKPASS environment variable is set, it specifies the path to the helper program. # Path to askpass helper program Path askpass /usr/X11R6/bin/ssh-askpass* – Scary Wombat Jan 18 '19 at 04:55
  • For more information on the askpass option, see https://stackoverflow.com/questions/21659637/how-to-fix-sudo-no-tty-present-and-no-askpass-program-specified-error, specifically rodrigo's answer. I understand that question doesn't have java in it, but it's really just a sudo question. – Ed Grimm Jan 18 '19 at 06:34
  • @ScaryWombat Tried it with -A option but didn't work – Abbas Jan 18 '19 at 07:47
  • see also this answer https://stackoverflow.com/a/29352596/2310289 – Scary Wombat Jan 18 '19 at 07:52

0 Answers0