Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有办法让用户';在Linux机器上使用java的UID?_Java_Linux_Uid - Fatal编程技术网

有没有办法让用户';在Linux机器上使用java的UID?

有没有办法让用户';在Linux机器上使用java的UID?,java,linux,uid,Java,Linux,Uid,有没有一种方法可以使用java在Linux机器上获取用户的UID?我知道System.getProperty(“user.name”)方法,但它返回的是用户名,我正在查找UID。您可以执行id命令并读取结果 例如: $id-u jigar 输出: 一千 您可以通过以下方式执行命令: try { String userName = System.getProperty("user.name"); String command = "id -u "+userName; Pro

有没有一种方法可以使用java在Linux机器上获取用户的UID?我知道
System.getProperty(“user.name”)
方法,但它返回的是用户名,我正在查找UID。

您可以执行
id
命令并读取结果

例如:

$id-u jigar

输出:

一千

您可以通过以下方式执行命令:

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");
问候,


Martin。

只需打开
/etc/passwd
文件,搜索用户等于
System.getProperty(“user.name”)
的行。另一种选择是使用JNI调用getuid()。

实际上有一个api用于此操作。不需要调用shell命令或使用JNI,只要

def uid = new com.sun.security.auth.module.UnixSystem().getUid()

如果您执行“id-n”
id-u
将只打印UID,那么解析就会容易得多。OP已经有了来自
System.getProperty(“user.name”)
@Anto的用户名。因此,有很多可能使用它,但在使用其他方法保存用户数据库的系统(如or等)上不起作用。(通常用于集群)这看起来是特定于Oracle的,而且也不适用于OpenJDK中的OpenJDKWorks,在Mac和Linux上的java-11-OpenJDK-devel-11.0.3.7上进行了测试,但我对Solaris有疑问。