1

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.

5
  • Can your task be solved by running your java from some .sh file with setuid bit and making root as file owner? Just asking cause you won't need to bother with sudo then Commented Sep 2, 2016 at 23:11
  • Thanks, I would like to accept Roman's answer, but there's no check mark as per docs: "click on the check mark beside the answer". Any ideas why? Commented Sep 3, 2016 at 7:34
  • That's because it was a comment, not an answer. Now I added an answer. Commented Sep 3, 2016 at 8:12
  • 1
    While piping via echo might work, it’s strongly discouraged as other processes can see the commandline, hence the password, while the process is running. Since the Java Process API already provides you with a pipe, there is no need to create another one. Just run sudo as sub-process and use process.getInput().write(/*password as bytes plus \n */) Commented Sep 5, 2016 at 10:08
  • @the.Legend - Setuid root scripts are VERY dangerous. unix.stackexchange.com/a/2910/1269 Commented Nov 25, 2017 at 0:02

2 Answers 2

2

Old question but instead of trying to echo password you should setup your sudoers file to allow just that command with no password for that user

myusername ALL = (root) NOPASSWD: /path/to/my/program

https://unix.stackexchange.com/questions/18830/how-to-run-a-specific-program-as-root-without-a-password-prompt

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.