How to enter password in sudo using java Runtime?

I need to execute given commands as root and sudo user using Java. However, I am not sure about the method I can use to pass the password. Is there a way that I can pass the password to the terminal?

+1


source to share


7 replies


You can just uninstall sodu all together and create a suid root shell script and run that instead.

chmod +s myscript && chown root myscript && chgrp root myscript

      



when the script is called, it will run as root.

+1


source


You can configure sudo to allow a specific command to run without a password. It doesn't require you to know the password.



Having a root password in a program, which should be clear text at some point, is actually less secure IMHO.

+3


source


Usually sudo reads the password by working directly on the terminal. This is where you should use sudo -S

. With this option it will try to read the password from stdin and then you can send it via OutputStream

which you get from the Process

one generated Runtime.exec()

when you run your command.

+1


source


Getting from one machine to another using ssh or scp can be done if you configure ssh without a password. This is one of the techniques used for clusters of machines that need to work together and are managed by a node head. For example hasoop uses this method.

+1


source


Better if you create a script in the terminal and call it from Java (using Runtime.exec)

0


source


As mentioned, you can sudo

only use if your current usage is configured in the system as such that can work sudo

. Otherwise (in general) you must enter a password.

You need to enter a password if you want to also run commands on remote computers using ssh

or copy files using scp

.

Some commands can accept a password as a command line parameter. For example, a utility mysql

can accept a password after switching -p

. Some of the other commands are stricter: they do not exclude the password on the command line, and they do not even allow you to enter the password through the stdin redirection of the process. Examples are ssh

and scp

.

The only way to make sure that you can always programmatically run any command that requires a password is to emulate a terminal. This is what the utility does expect

. Take a look at his man page: http://linux.die.net/man/1/expect

I have used expect

in the past. it is a managed script utility that allows you to simulate user actions just like the user-to-user does when he is working with the terminal. We ran the expected script from java as a normal external process using ProcessBuilder

.

0


source


I needed to use ProcessBuilder to run tcpdump. This is how I did it:

visudo myuser ALL = NOPASSWD: / usr / sbin / tcpdump

Then my command from Java was, which was run from myuser: / usr / bin / sudo / usr / sbin / tcpdump -i eth0 port 8561 ...

0


source







All Articles