有没有办法在使用java的Linux机器上获取用户的UID?

kof*_*cii 11 java linux uid

有没有办法在使用java的Linux机器上获取用户的UID?我知道System.getProperty("user.name");方法,但它返回的用户名,我正在寻找UID.

Jig*_*shi 12

你可以执行id命令和读取结果.

例如:

$ id -u jigar

输出:

1000

你可以执行命令

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) {
}
Run Code Online (Sandbox Code Playgroud)

资源

  • `id -u <user>` 只会打印 UID。 (2认同)

Eri*_*ino 11

实际上有一个 api 可以实现这一点。无需调用 shell 命令或使用 JNI,只需

def uid = new com.sun.security.auth.module.UnixSystem().getUid()
Run Code Online (Sandbox Code Playgroud)


小智 6

如果您可以影响 Java VM 的启动方式,您可以将uid作为用户属性进行切换:

java -Duserid=$(id -u) CoolApp
Run Code Online (Sandbox Code Playgroud)

在您的 CoolApp 中,您可以简单地通过以下方式获取 ID:

System.getProperty("userid");
Run Code Online (Sandbox Code Playgroud)

问候,

马丁。