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

时间:2012-12-24 00:24:27

标签: java linux command-line sudo

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

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

因此,执行此操作的过程包含三个步骤:

  1. 在终端
  2. 输入sudo vim /etc/resolv.conf
  3. 终端要求我输入我的root密码
  4. 我输入密码并按[Enter]
  5. 从我研究的所有内容中,我可以使用以下内容执行上述步骤#:

    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)。提前谢谢。

2 个答案:

答案 0 :(得分:8)

您是否尝试过-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.

答案 1 :(得分: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的回答。