Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to supply sudo with root password from Java?

I'm trying to write a small Java app that will overwrite my /etc/resolv.conf file (I'm on Ubuntu 12.04). To do so, I need to supply my root password:

myUser@myMachine:~$ sudo vim /etc/resolv.conf 
[sudo] password for myUser: *****

So the process for doing this has three steps:

  1. Type sudo vim /etc/resolv.conf at terminal
  2. Terminal asks me to type my root password
  3. I enter the password and press [Enter]

From everything I've researched, I could use the following for performing step #1 above:

try {
    String installTrickledCmd = "sudo vim /etc/resolv.conf";
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec(installTrickledCmd);
}
catch(Throwable throwable) {
    throw new RuntimeException(throwable);
}

But when this executes, the shell will want to prompt my Java process for the password. I'm not sure how to wait for this (step #2 above) and then to supply my password back to the shell (step #3 above). Thanks in advance.

like image 762
IAmYourFaja Avatar asked Jan 14 '23 16:01

IAmYourFaja


1 Answers

Have you tried with -S ?

$echo mypassword | sudo -S vim /etc/resolv.conf

From man:

The -S (stdin) option causes sudo to read the password from the standard input 
instead of the terminal device.  The password must be followed by a newline 
character.
like image 134
Luigi R. Viggiano Avatar answered Jan 20 '23 13:01

Luigi R. Viggiano