如何与从Java root密码提供须藤?(How to supply sudo with root

2019-08-04 14:17发布

我试图写一个小的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);
}

但这个执行时,外壳会想提示我的Java程序的密码。 我不知道如何等待这个(上述步骤#2),然后提供我的密码回到壳(上面的步骤#3)。 提前致谢。

Answer 1:

你有没有用-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.


Answer 2:

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();
      }
    }
  }

}

从维贾诺答案启发。



文章来源: How to supply sudo with root password from Java?