Search code examples
javajava-8iptablesprocessbuilder

Run sudo command using Java processBuilder


I need to run a sudo command from within java, and redirect the output to a file, using processbuilder or similar.

Two questions:

  1. Will piping the sudo password using echo work as follows?
  2. 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.


Solution

  • First, you need to use -S with sudo to make it read the password from its stdin.
    Second, you should read or redirect the error stream somewhere to be aware of any errors.