I need to run a sudo command from within java, and redirect the output to a file, using processbuilder or similar.
Two questions:
- Will piping the sudo password using echo work as follows?
Although the file gets created, nothing is ever written to it. Any ideas why?
ProcessBuilder conntrack_process = new ProcessBuilder("/bin/bash", "-c", "echo '<passwordhere>' | sudo conntrack -L"); conntrack_process.redirectOutput(new java.io.File("/home/<homedir>/conntrack_out.txt")); Process ct_process = conntrack_process.start(); ct_process.waitFor(); ct_process.destroy();
I am using Ubuntu 16.04.
echomight work, it’s strongly discouraged as other processes can see the commandline, hence the password, while the process is running. Since the JavaProcessAPI already provides you with a pipe, there is no need to create another one. Just runsudoas sub-process and useprocess.getInput().write(/*password as bytes plus \n */)…