有没有一种方法在Linux机器上使用Java获取用户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) {
}
实际上有一个 API 可以做到这一点。不需要调用 shell 命令或使用 JNI,只需
def uid = new com.sun.security.auth.module.UnixSystem().getUid()
java -Duserid=$(id -u) CoolApp
System.getProperty("userid");
敬礼,
马丁。
另一个选择是使用JNI调用getuid()。
为了完整起见,这里提供一个仅使用Java的解决方案,无需任何JNI、子进程或私有API。
警告:这依赖于用户主目录,而不需要与当前运行的Java进程所有者匹配。在盲目依赖此功能之前,请确保您的目标系统环境:
Path userHome = Paths.get(System.getProperty("user.home"));
int uid = (Integer)Files.getAttribute(userHome, "unix:uid")
(Integer)Files.getAttribute(Paths.get("/proc/self"), "unix:uid")
可以用于获取正在运行的进程的UID。 - user3076105
System.getProperty("user.name")
获取了用户名。 - dogbane