我有一个带有
USER_PW=xxx
的配置文件 Secrets.properties 文件,我希望将密码传递给执行需要 root 权限的命令的进程。
尝试以两种不同的方式传递密码。在第一个代码片段中,我的密码被打印到终端,而不是传递到管道。
// Process Builder
ProcessBuilder pb = new ProcessBuilder();
String cmd = "cp";
String tableName = "password_entries.ibd";
String source = properties.getProperty("DB_PATH");
String target = ".";
String userPassword = secrets.getProperty("USER_PW");
try {
pb.inheritIO();
// elevate privileges to root
pb.command("echo", userPassword, "|", "sudo", "-S", "echo", "test");
pb.start().waitFor();
// cp to host
pb.command("sudo", "-S", cmd, source + tableName, target);
pb.start().waitFor();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
在第二个中,其他东西不起作用。我认为这是因为密码是通过
<<<
提供的,周围没有 ""
。
终端上的正确调用是:
sudo -S <<< "password" echo Test
,但我不知道如何提供密码周围的""
。
我也尝试了
pb.command("sudo", "-S", "<<<", "\"" + userPassword + "\"", "echo", "test");
但是sudo仍然提示输入密码。
// Process Builder
ProcessBuilder pb = new ProcessBuilder();
String cmd = "cp";
String tableName = "password_entries.ibd";
String source = properties.getProperty("DB_PATH");
String target = ".";
String userPassword = secrets.getProperty("USER_PW");
try {
pb.inheritIO();
// elevate privileges to root
pb.command("sudo", "-S", "<<<", userPassword, "echo", "test");
pb.start().waitFor();
// cp to host
pb.command("sudo", "-S", cmd, source + tableName, target);
pb.start().waitFor();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
我找到了解决方案:
// Process Builder
ProcessBuilder pb = new ProcessBuilder();
String cmd = "cp";
String tableName = "password_entries.ibd";
String source = properties.getProperty("DB_PATH");
String target = ".";
String userPassword = secrets.getProperty("USER_PW");
try {
// elevate privileges to root
pb.command("sudo", "-S", "echo", "test");
Process p = pb.start();
p.getOutputStream().write((userPassword + "\n").getBytes());
p.getOutputStream().flush();
p.waitFor();
// cp to host
pb.command("sudo", "-S", cmd, source + tableName, target);
pb.start().waitFor();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}