13

Is there a way to get user's UID on Linux machine using java? I'm aware of System.getProperty("user.name"); method, but it return's user name and I'm looking for UID.

Paul Rubel
  • 24,802
  • 7
  • 54
  • 76
kofucii
  • 6,579
  • 12
  • 47
  • 77

5 Answers5

13

you can execute id command and read result.

for example:

$ id -u jigar

output:

1000

you can execute command by

try {
    String userName = System.getProperty("user.name");
    String command = "id -u "+userName;
    Process child = Runtime.getRuntime().exec(command);

    // Get the input stream and read from it
    InputStream in = child.getInputStream();
    int c;
    while ((c = in.read()) != -1) {
        process((char)c);
    }
    in.close();
} catch (IOException e) {
}

source

jmj
  • 225,392
  • 41
  • 383
  • 426
5

If you can influence how the Java VM is started, you could handover the uid as a user property:

java -Duserid=$(id -u) CoolApp

In your CoolApp, you could simply fetch the ID with:

System.getProperty("userid");

Regards,

Martin.

4

There is actually an api for this. There is no need to call a shell command or use JNI, just

def uid = new com.sun.security.auth.module.UnixSystem().getUid()
Erik Martino
  • 3,561
  • 1
  • 15
  • 11
1

Just open the /etc/passwd file and search for the line that has a user equal to System.getProperty("user.name").

vz0
  • 30,291
  • 7
  • 37
  • 74
  • 1
    that does not work on systems using other methods for keeping the user database e.g. [NIS](http://en.wikipedia.org/wiki/Network_Information_Service) or [LDAP](http://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol) etc. (typically used on clusters) – Andre Holzner Jul 17 '13 at 13:23
1

Another choice would be calling getuid() using JNI.

Volker Stolz
  • 6,914
  • 29
  • 47