有没有办法使用java在Linux机器上获取用户的UID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4796172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to get user's UID on Linux machine using java?
提问by kofucii
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.
有没有办法使用java在Linux机器上获取用户的UID?我知道System.getProperty("user.name");
方法,但它返回用户名,我正在寻找 UID。
采纳答案by Jigar Joshi
you can execute id
command and read result.
您可以执行id
命令并读取结果。
for example:
例如:
$ id -u jigar
$ id -u jigar
output:
输出:
1000
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) {
}
回答by Jigar Joshi
If you can influence how the Java VM is started, you could handover the uidas a user property:
如果您可以影响 Java VM 的启动方式,您可以将uid作为用户属性进行切换:
java -Duserid=$(id -u) CoolApp
In your CoolApp, you could simply fetch the ID with:
在您的 CoolApp 中,您可以简单地通过以下方式获取 ID:
System.getProperty("userid");
Regards,
问候,
Martin.
马丁。
回答by vz0
Just open the /etc/passwd
file and search for the line that has a user equal to System.getProperty("user.name")
.
只需打开/etc/passwd
文件并搜索用户等于 的行System.getProperty("user.name")
。
回答by Volker Stolz
Another choice would be calling getuid() using JNI.
另一种选择是使用 JNI 调用 getuid()。
回答by Erik Martino
There is actually an api for this. There is no need to call a shell command or use JNI, just
实际上有一个 api。无需调用shell命令或使用JNI,只需
def uid = new com.sun.security.auth.module.UnixSystem().getUid()