How to input password to sudo using java Runtime?

2019-01-20 16:35发布

问题:

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

回答1:

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

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

whenever that script is called it will be run as root.



回答2:

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

Having the root password in the program which has to be clear text at some stage is actually less secure IMHO.



回答3:

Normally sudo reads the password by operating directly on the terminal. You should use sudo -S here. With this option, it will try to read the password from standard input and then you can send it via the OutputStream you get from the Process created by Runtime.exec() when you run your command.



回答4:

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



回答5:

It will be better if you create a script on the terminal and call it from Java(using Runtime.exec)



回答6:

As guys already mentioned you can use sudo only if your current use is configured at the system as one that can run sudo. Otherwise (in general case) you have to type password.

You have to type password if you want to run commands on remote computers as well using ssh or copy files remotely using scp.

Some commands can accept password as a parameter of command line. For example mysql utility can accept password after switch -p. Some other commands are more strict: they do not exept password in command line and even do not allow you to supply password via redirecting of stdin of the process. Examples are ssh and scp.

The only way to be sure that you can always programmatically run any command that requires typing the password is to emulate the terminal. This is what utility expect does. Take a look on its man page: http://linux.die.net/man/1/expect

I used expect in past. it is script driven utility that allows simulating user's actions exactly as human user is doing when he is working with terminal. We ran the expect script from java as regular external process using ProcessBuilder.



回答7:

I needed to use ProcessBuilder to run tcpdump. Here 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 ...