4

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

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

因此,执行此操作的过程分为三个步骤:

  1. sudo vim /etc/resolv.conf在终端输入
  2. 终端要求我输入root密码
  3. 我输入密码并按[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 进程输入密码。我不确定如何等待(上面的步骤#2)然后将我的密码提供回shell(上面的步骤#3)。提前致谢。

4

2 回答 2

9

你试过 -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.
于 2012-12-24T00:33:52.673 回答
0
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 的回答。

于 2017-05-26T14:55:33.543 回答