我正在尝试编写一个覆盖我的/etc/resolv.conf
文件的小型Java应用程序(我在Ubuntu 12.04上)。为此,我需要提供我的root
密码:
myUser@myMachine:~$ sudo vim /etc/resolv.conf
[sudo] password for myUser: *****
因此,执行此操作的过程包含三个步骤:
sudo vim /etc/resolv.conf
root
密码[Enter]
从我研究的所有内容中,我可以使用以下内容执行上述步骤#:
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)。提前谢谢。
答案 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的回答。