Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running UNIX commands as different user, from Java

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.

like image 602
Glen Balliet Avatar asked Jun 18 '09 14:06

Glen Balliet


2 Answers

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.

like image 60
DevSolar Avatar answered Oct 16 '22 09:10

DevSolar


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!

like image 33
Glen Balliet Avatar answered Oct 16 '22 09:10

Glen Balliet