19

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
  • 26,632
  • 7
  • 60
  • 80
kofucii
  • 7,393
  • 12
  • 51
  • 79

6 Answers6

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
  • 237,923
  • 42
  • 401
  • 438
11

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
  • 4,023
  • 1
  • 19
  • 12
6

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.

2

Another choice would be calling getuid() using JNI.

Volker Stolz
  • 7,274
  • 1
  • 32
  • 50
2

Just for the sake of completeness, here is a Java-only solution without any need for JNI, child processes or private API.

A word of warning: This relies on the user home directory, which is not at all required to match the owner of the currently running Java process. Be sure about your targeted system environment, before blindly relying on this:

Path userHome = Paths.get(System.getProperty("user.home"));
int uid = (Integer)Files.getAttribute(userHome, "unix:uid")
Sebastian S
  • 4,420
  • 4
  • 34
  • 63
  • 1
    On some systems (e.g. Linux) `(Integer)Files.getAttribute(Paths.get("/proc/self"), "unix:uid")` works for running process's UID – user3076105 May 19 '23 at 21:51
1

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

vz0
  • 32,345
  • 7
  • 44
  • 77
  • 2
    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