tags:

views:

68

answers:

2

Here's the situation. I have a jython 2.1 script in a shared account that needs to know who is calling it. In bash, I can simply use $(who -m) and it will give me the correct username.

By "shared account", I mean I log in as myself, then $(sudo su - shared_account) to get to the shared account.

I haven't been able to find anything in java (or jython) that would give me a similar result. Even trying to call Runtime.getRuntime().exec("who -m") doesn't do anything. When I try to read the InputStream from the process returned by exec, the stream is empty.

+3  A: 

To get the process owner do this:

System.getProperty("user.name");

The syntax of getRunTime().exec() is tricky.

Runtime.getRuntime().exec(new String[] {"/path/to/who", "-m"});
Marcus Adams
Not sure (but definitely too lazy to check), but I think this returns the process' owner, and not stdin's owner (as `who -m` does)
Romain
Exactly. I'm trying to get the stdin owner name (the account I originally logged in to), not the process owner name (the account I switched to with sudo).
amertune
@Romain, you're right, according to docs, it's `User's account name`.
Marcus Adams
The problem with Runtime.exec is that it doesn't seem to know who owns stdin. There is no output from 'who -m' in java.
amertune
@amertune, did you pass in the path and arguments separately for getRuntime().exec()?
Marcus Adams
From java.sun.com:public Process exec(String command) throws IOExceptionExecutes the specified string command in a separate process.The command argument is parsed into tokens and then executed as a command in a separate process. The token parsing is done by a StringTokenizer created by the call: new StringTokenizer(command)If you pass the entire command with flags, then it will be tokenized. Essentially, exec("/path/to/who -m") works the same as exec(new String[] {"/path/to/who", "-m"})
amertune
A: 

I've come up with an option, even though I don't really love it:

Add this flag to the java call:

-Duser.name="$(who -m | awk '{print $1}')"

And then access the user name with:

System.getProperty('user.name')
amertune
@amertune, pretty neat. Please note that I updated my answer with an example for getRunTime().exec().
Marcus Adams
Good idea ... but please **use a different property name**. Other code and other programmers expect the `"user.name"` property to contain the name of the process owner.
Stephen C