如何从Java提供root密码的sudo?

我想写一个小的Java应用程序,将覆盖我的/etc/resolv.conf文件(我在Ubuntu 12.04上)。 为此,我需要提供我的root密码:

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

所以这个过程有三个步骤:

  1. 在terminal键入sudo vim /etc/resolv.conf
  2. terminal要我input我的root密码
  3. 我input密码并按[Enter]

从我研究过的所有东西,我可以使用以下步骤来执行上面的步骤#1:

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

但是当这个执行的时候,shell会要求我的Java进程input密码。 我不知道该如何等待(步骤#2),然后将密码提供给shell(上面的步骤#3)。 提前致谢。

Solutions Collecting From Web of "如何从Java提供root密码的sudo?"

你用S试过了吗?

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

从男人:

 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. 
 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; public class Test1 { public static void main(String[] args) throws Exception { String[] cmd = {"sudo","-S", "ls"}; System.out.println(runSudoCommand(cmd)); } private static int runSudoCommand(String[] command) throws Exception { Runtime runtime =Runtime.getRuntime(); Process process = runtime.exec(command); OutputStream os = process.getOutputStream(); os.write("harekrishna\n".getBytes()); os.flush(); os.close(); process.waitFor(); String output = readFile(process.getInputStream()); if (output != null && !output.isEmpty()) { System.out.println(output); } String error = readFile(process.getErrorStream()); if (error != null && !error.isEmpty()) { System.out.println(error); } return process.exitValue(); } private static String readFile(InputStream inputStream) throws Exception { if (inputStream == null) { return ""; } StringBuilder sb = new StringBuilder(); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = bufferedReader.readLine(); while (line != null) { sb.append(line); line = bufferedReader.readLine(); } return sb.toString(); } finally { if (bufferedReader != null) { bufferedReader.close(); } } } } 

启发Viggiano的答案。