AlwaysALearner
AlwaysALearner

Reputation: 6690

sudo command using java not working

I have this code to execute a command with and without using sudo option

String sudoScript = "sudo -u root -S ls /";
String script = "ls /";
try {
    System.out.println("===================================");
    System.out.println("command="+sudoScript);
    Process p1 = Runtime.getRuntime().exec(sudoScript);
            System.out.println("p2.waitFor()="+p1.waitFor());
    BufferedReader stdInput1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
    while ((sudoScript = stdInput1.readLine()) != null) {
            System.out.println(script);
    }
    System.out.println("===================================");
    System.out.println("command="+script);
    Process p2 = Runtime.getRuntime().exec(script);
            System.out.println("p2.waitFor()="+p2.waitFor());
    BufferedReader stdInput2 = new BufferedReader(new InputStreamReader(p2.getInputStream()));
    while ((script = stdInput2.readLine()) != null) {
            System.out.println(script);
    }
} catch (Exception e) {
    e.printStackTrace();
}

And this is the kind of output I get-

===================================
command=sudo -u root -S ls /
p2.waitFor()=1
===================================
command=ls /
p2.waitFor()=0
bin
boot
cgroup
data
dev
etc
home
home.save
lib
lost+found
media
mnt
null
opt
opt.save
proc
root
sbin
selinux
srv
sys
tmp
usr
var

If you observe, I'm not able to get the same output using sudo command. Is there something I've missed here?

Upvotes: 2

Views: 3658

Answers (3)

akostadinov
akostadinov

Reputation: 18604

Nowadays most distros have sudo configured to require tty to execute.

try (within /etc/sudoers):

Defaults    requiretty

or

Defaults!/path/to/program !requiretty

You need to make sure sudo does not require a password for that user for that particular command (e.g. ls /) or you need to supply it to sudo.

UPDATE: btw, it is a good idea to read stderr as well so we don't have to guess what is wrong with command execution

Upvotes: 1

diestl
diestl

Reputation: 2058

The command sudo -u root -S ls / prompts for the user password.

Something like echo '[password]' | sudo -u root -S ls / might do the trick.

Note: This requires hard-coding the password. Which is probably not the best idea.

EDIT: According to man sudo, the -u root option is unnecessary. Running sudo -S ls / will have the same effect.

Upvotes: 0

Roo
Roo

Reputation: 427

you should be able to pipe in a password to the sudo command.

Upvotes: 0

Related Questions