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

邮差的信 提交于 2019-12-08 16:25:35

问题


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.


回答1:


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




回答2:


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.




回答3:


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




回答4:


Another choice would be calling getuid() using JNI.




回答5:


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()


来源:https://stackoverflow.com/questions/4796172/is-there-a-way-to-get-users-uid-on-linux-machine-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!