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

有帮助吗?

解决方案

您可以执行 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) {
}

资源

其他提示

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

java -Duserid=$(id -u) CoolApp

在您的Coolapp中,您可以简单地获取ID:

System.getProperty("userid");

问候,

马丁。

只需打开即可 /etc/passwd 文件并搜索具有等于用户的行 System.getProperty("user.name").

另一个选择是使用jni调用getUid()。

实际上有一个API。无需调用外壳命令或使用JNI,只是

def uid = new com.sun.security.auth.module.UnixSystem().getUid()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top