Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get user's UID on Linux machine using java?

Tags:

java

linux

uid

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.

like image 966
kofucii Avatar asked Jan 25 '11 16:01

kofucii


People also ask

How do you find UID of a user in Linux?

You can find UID stored in the /etc/passwd file. This is the same file that can be used to list all the users in a Linux system. Use a Linux command to view text file and you'll see various information about the users present on your system. The third field here represents the user ID or UID.

How do I find my user's UID?

Where to find stored UID? You can find the UID in the /etc/passwd file, which is the file that also stores all users registered in the system. To view the /etc/passwd file contents, run the cat command on the file, as shown below on the terminal.


2 Answers

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

like image 157
jmj Avatar answered Sep 19 '22 16:09

jmj


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()
like image 37
Erik Martino Avatar answered Sep 20 '22 16:09

Erik Martino