我正在使用ProcessBuilder和Runtime.exec对sudo调用命令进行挑战。我认为ProcessBuilder总体上是更好的解决方案,但两者都产生相同的结果 - 它们在Ubuntu上执行shell命令很好,但是如果我尝试执行sudo -i mysql命令,例如:
public static void runProcess(String[] process) {
String s = null;
try {
Process p = new ProcessBuilder(process).start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) { System.out.println(s); }
while ((s = stdError.readLine()) != null) { System.out.println(s); }
} catch (IOException e) { e.printStackTrace(); }
}
这两个命令有效:
String[] cmdArgs0 = { "sudo", "echo", "Done" };
runProcess(cmdArgs0);
String[] cmdArgs1 = { "bash", usbDrivePath+"/ASWebUI/Install.sh" };
runProcess(cmdArgs1);
但这不是:
String[] cmdArgs2 = { "sudo", "-i", "mysqldump", "Core", ">", cachePath+"/SQLDumps/Core.sql" };
runProcess(cmdArgs2);
错误:
mesg: ttyname failed: Inappropriate ioctl for device
mysqldump: Couldn't find table: ">"
答案 0 :(得分:1)
ProcessBuilder不允许您使用>
字符重定向输出。相反,您可以使用processBuilder.redirectOutput()
方法指定所需的输出。
File dumpFile = new File("Core.sql");
processBuilder.redirectOutput(Redirect.to(dumpFile));
甚至使用mysqldump的--result-file
选项来指定转储文件:
mysqldump [options] --result-file=dump.sql