How to enter password in sudo using java Runtime?
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.
source to share
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
.
source to share