Running UNIX commands as different user, from Java

2019-01-17 22:03发布

问题:

Trying to write a Java program capable of running a UNIX command as a different UNIX user. I have the user's password, and I know the command I want to run, but the command has to be run as that user - so I have to login as that user first.

For example: say we have a user, jim, who wants to see what's in bob's home directory, and (for whatever reason) jim has access to execute ls whereas bob does not. We are currently logged in as bob. Here is what we (could) do:

bob@host$ su jim && ls ~bob

Problem is, we get prompted for jim's password. Since this is run from a Java program, i.e.

Process p = Runtime.getRuntime().exec("su jim && ls ~bob");

we get prompted for jim's password and hung up. We know jim's password. However, I can't enter it.

Additionally, we can't use an Expect script (don't have it installed) and we can't become the superuser. I also looked into using SSH to try this, since we could technically do

bob@host$ ssh jim@host "ls ~bob"

but this also doesn't work since I don't have permission to setup passwordless SSH.

My last-ditch effort is to try and use an SSH library for Java, since the password is available to the Java program and I would be able to login with that (and execute the proper command). But since I'm going to be running on the same host, it seems like overkill.

Any suggestions?

P.S: Java version 1.4.2, can't upgrade; AIX UNIX 5.3.

回答1:

Have sudo installed, have the user running the Java program entered in /etc/sudoers for the commands in question, and use sudo -u jim ls ~bob.



回答2:

Problem solved. Used JSch (http://www.jcraft.com/jsch/) to SSH into the server with known username and password, and execute command. Thanks all for your suggestions!



回答3:

Possibly a java implementation of Expect? ExpectJ comes up when googling but I couldn't find any documentation regarding running under 1.4.2.



回答4:

Have you tried redirecting the sudo commands input and writing to that. I haven't used Java in a while but I believe there is a way to get the input stream and write to it. You could use that to write the password followed by a new line and sudo or su should accept the password.

Use getInputStream() and write your password out to that.

su jim -c ls ~Bob


回答5:

Perhaps this would work:

Process process = Runtime.getRuntime().exec("su jim && ls ~bob");

OutputStream standardInput = process.getOutputStream();
Writer standardInputWriter = new OutputStreamWriter(standardInput);
standardInputWriter.write("password\n");
standardInputWriter.close();


回答6:

I'm not sure this code:

Process p = Runtime.getRuntime().exec("su jim && ls ~bob");

will be executed in a shell, needed to evaluate the &&, that is a shell command (/bin/sh). You should pass the command "ls ~bob" via a command line swith of su. Something like:

su jim -c 'ls ~bob'