Run the linux shell command using "sudo" using java without entering the required password

Hi, I am using ganymed-ssh2 java library to successfully execute remote commands on a Linux workstation.

But now there is a situation where I need to execute a command, but this requires me to add a password ... for example:

sudo /usr/bin/some_process please enter your password: 

I used to execute remote cmd as follows:

 Session sess = conn.openSession(); sess.execCommand("uname -a && date && uptime && who"); System.out.println("Here is some information about the remote host:"); InputStream stdout = new StreamGobbler(sess.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); while (true) { String line = br.readLine(); if (line == null) break; System.out.println(line); } System.out.println("ExitCode: " + sess.getExitStatus()); sess.close(); conn.close(); 

I am afraid that it is impossible to execute commands that require a password with this library.

Someone can give me a solution or an alternative to resolve this.

thanks!

+4
source share
3 answers

Assuming sess.getStdin() exists, you should be able to attach a password to the sudo command.

+2
source

The simplest solution is to provide the user with the Java program registered as being able to run this sudo command without entering a password. You can do this by running visudo on the host and entering NOPASSWD after this command. See man 8 visudo more details.

+1
source

The easiest way to do this is probably to use public key authentication . Therefore, you do not need a password.

Edit: I was misled that this question was about SSH, when it really is about sudo. In this case, the kojiro solution is correct: edit the /etc/sudoers file, use the NOPASSWD flag.

0
source

Source: https://habr.com/ru/post/1342001/


All Articles