I have a config file secrets.properties file with USER_PW=xxx and I wold like to pass the password to a process that executes a command that requires root privileges.
In tried to pass the password in two different ways. In the first code snippet my password is printed to the terminal, instead of passed to the pipe.
// 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);
}
In the second one something else does not work. I think it is because the password is provided via <<< without the "" around it.
The correct call on the terminal is: sudo -S <<< "password" echo Test but I don't know how to provide the "" around the password.
I also tried pb.command("sudo", "-S", "<<<", "\"" + userPassword + "\"", "echo", "test"); but the sudo still prompts for the password.
// 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);
}
bash -c echo foo | barThe same goes for redirectionspb.command("/bin/bash", "-c", "echo '%s' | sudo -S whoami".formatted(password));pb.inheritIO();that means the terminal shows information. Alsopswill see the password (albeit briefly in some cases)new ProcessBuilder("bash", "-c", "sudo -S < /tmp/password-file cat /etc/sudoers").inheritIO().start();It might be an idea to make more use of the file that's the subject ofcatin the above